我在 TikZ 中使用相对定位时遇到问题。如下面的 MWE 所示,当使用 \node[right = of ...] 语法并排放置两个图形时,我的“顶点圆”放置不正确。
使用“right = of ...”语法的代码:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}
\tikzset{
vertex/.style={circle,fill=black,minimum size=.8mm,inner sep=0pt}
}
\begin{document}
\begin{tikzpicture}
\node (2nd_1) at (0,0) {
\tikz{
\coordinate (u1) at (0,0);
\coordinate[below= of u1] (l1);
\coordinate[right= of u1] (u2);
\coordinate[right= of l1] (l2);
%
\draw (u1) -- (l1);
\draw (u2) -- (l2);
\draw (l1) -- (l2);
\draw (l1) node[vertex]{};
\draw (l2) node[vertex]{};
}
};
\node[right=0 of 2nd_1] (2nd_2) {
\tikz{
\coordinate (u1) at (0,0);
\coordinate[below= of u1] (l1);
\coordinate[right= of u1] (u2);
\coordinate[right= of l1] (l2);
%
\draw (u1) -- (l1);
\draw (u2) -- (l2);
\draw (l1) -- (l2);
\draw (l1) node[vertex]{};
\draw (l2) node[vertex]{};
}
};
\end{tikzpicture}
\end{document}
手动设置位置的代码:
\begin{tikzpicture}
\node (2nd_1) at (0,0) {
\tikz{
\coordinate (u1) at (0,0);
\coordinate[below= of u1] (l1);
\coordinate[right= of u1] (u2);
\coordinate[right= of l1] (l2);
%
\draw (u1) -- (l1);
\draw (u2) -- (l2);
\draw (l1) -- (l2);
\draw (l1) node[vertex]{};
\draw (l2) node[vertex]{};
}
};
\node (2nd_2) at (1.5,0) {
\tikz{
\coordinate (u1) at (0,0);
\coordinate[below= of u1] (l1);
\coordinate[right= of u1] (u2);
\coordinate[right= of l1] (l2);
%
\draw (u1) -- (l1);
\draw (u2) -- (l2);
\draw (l1) -- (l2);
\draw (l1) node[vertex]{};
\draw (l2) node[vertex]{};
}
};
\end{tikzpicture}
左图:使用“right = of”语法。右图:手动定位
从图片中可以明显看出,左侧第二个图形上的顶点圆放置不正确。我似乎无法弄清楚错误源自何处,因此任何帮助/解释都值得感激。
答案1
消息的另一个案例研究:不要嵌套 tikzpictures!\tikz{}
由于处于同一范围内,内容继承了节点选项,因此它不会启动tikzpicture
环境的全新副本。
如果您想将事物分组在一起,请使用范围并转移范围。
\documentclass[tikz]{standalone}
\usetikzlibrary{positioning}
\tikzset{vertex/.style={circle,fill=black,minimum size=.8mm,inner sep=0pt}}
\begin{document}
\begin{tikzpicture}
\coordinate (u1) at (0,0);
\coordinate[below= of u1] (l1);
\coordinate[right= of u1] (u2);
\coordinate[right= of l1] (l2);
%
\draw (u1) -- (l1);
\draw (u2) -- (l2);
\draw (l1) -- (l2);
\draw (l1) node[vertex]{};
\draw (l2) node[vertex]{};
\begin{scope}[shift={([xshift=1cm]u2)}]
\coordinate (u1) at (0,0);
\coordinate[below= of u1] (l1);
\coordinate[right= of u1] (u2);
\coordinate[right= of l1] (l2);
%
\draw (u1) -- (l1);
\draw (u2) -- (l2);
\draw (l1) -- (l2);
\draw (l1) node[vertex]{};
\draw (l2) node[vertex]{};
\end{scope}
\end{tikzpicture}
\end{document}