我正在编写脚本来根据输入数据构建图表,其中一个麻烦是将节点放置在最右边的节点的右边。
这是 MWE:
\documentclass[border=.5cm]{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}
\node at (0,0) [draw] (n1) {node1};
\node at (-1,1) [draw] (n2) {node2};
\node at (1,2) [draw] (n3) {node3};
\node at (0.5,-1) [draw] (n4) {node4};
\end{tikzpicture}
\end{document}
因此,我将多个节点放置在多行中。一行中只有一个节点。我需要将一个新节点放置在特定行中,但位于所有行中最右侧节点的右侧。在上面的示例中,我需要将一个节点放置在一行中n1
,但位于右侧 0.5 厘米处n3
(此节点是图片中所有节点中最右侧的节点)。
我可以使用低级命令来比较节点右角坐标,但也许有更简单的方法?
有什么建议么?
更新:
我可以使用let
命令来将节点相对于其他节点定位:
\path let \p1=(n3.south east), \p2=(n1.south east) in
node[anchor = south west, draw, xshift=.5cm] at (\x1,\y2) {node5};
但是我如何才能计算出最正确的节点?
更新2:
我尝试使用max
命令:
\path let \p1=(n1.south east),
\p2=(n2.south east),
\p3=(n3.south east),
\p4=(n4.south east) in
node[anchor = south west, draw, xshift=.5cm] at (max(\x1,\x2,\x3, \x4), \y2) {node5};
但收到以下错误:
! Package tikz Error: A node must have a (possibly empty) label text.
See the tikz package documentation for explanation.
Type H <return> for immediate help.
...
l.25 ...aw, xshift=.5cm] at (max(\x1,\x2,\x3,\x4),
\y2) {node5};
我究竟做错了什么?
答案1
您需要 来{}
包装。此外,分配给 的节点max(...)
似乎应该使用。OP 的代码会导致错误结果。n1
\p1
\y1
\y2
代码
\documentclass[border=.5cm]{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
\node at (0,0) [draw] (n1) {node1};
\node at (-1,1) [draw] (n2) {node2};
\node at (1,2) [draw] (n3) {node3};
\node at (0.5,-1) [draw] (n4) {node4};
\path let \p1=(n1.south east),
\p2=(n2.south east),
\p3=(n3.south east),
\p4=(n4.south east)
in node[anchor = south west, draw, xshift=.5cm] at ({max(\x1,\x2,\x3,\x4)}, \y1) {node5};
\end{tikzpicture}
\end{document}
答案2
代码
以下是我使用路径操作从 PGF 数学引擎let
访问坐标和函数的步骤:max()
\documentclass[border=.5cm]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
\node at (0,0) [draw] (n1) {node1};
\node at (-1,1) [draw] (n2) {node2};
\node at (1,2) [draw] (n3) {node3};
\node at (0.5,-1) [draw] (n4) {node4};
\path let \p1=(n1) in \pgfextra{\xdef\xNew{\x1}\xdef\yNew{\y1}}; % to get (n1) coordinates
\foreach \i in {2,...,4} % compute xNew
\draw let \p1=(n\i) in \pgfextra{\pgfmathparse{max(\x1,\xNew)}\xdef\xNew{\pgfmathresult}};
\node at (\xNew pt,\yNew) [draw, xshift=.5cm] (n5) {node5};
\end{tikzpicture}
\end{document}