我想用 tikz 制作以下简单图表:
我实际上更喜欢使用 tikz\for
循环将元素放在一起。但是,以下代码:
\begin{tikzpicture}[font=\small,>=latex,
add/.style={draw=black,circle,inner sep=0pt},
branch/.style={fill=black,circle,minimum size=3pt,inner sep=0pt}%
]
\foreach \i in {2,4,6,8} {%
\node[add] at (-1,\i) (add\i) {$+$};
}
\foreach \i[evaluate={\j=\i+1}] in {1,3,5,7} {%
\node[branch] at (-1,\i) (dot\i) {};
\draw[->] (dot\i) -- (add\j);
}
\end{tikzpicture}
产生错误的图形。也就是说,箭头尖端连接到加法器的右侧:
而如果我只是\draw[->]
在循环外手动编写部分代码,即使用以下代码:
\begin{tikzpicture}[font=\small,>=latex,
add/.style={draw=black,circle,inner sep=0pt},
branch/.style={fill=black,circle,minimum size=3pt,inner sep=0pt}%
]
\foreach \i in {2,4,6,8} {%
\node[add] at (-1,\i) (add\i) {$+$};
}
\foreach \i[evaluate={\j=\i+1}] in {1,3,5,7} {%
\node[branch] at (-1,\i) (dot\i) {};
}
\draw[->] (dot1) -- (add2);
\draw[->] (dot3) -- (add4);
\draw[->] (dot5) -- (add6);
\draw[->] (dot7) -- (add8);
\end{tikzpicture}
我得到了正确的结果(我在问题开头给出的结果)。有什么想法可以解释为什么连接循环内的节点会弄乱连接点?
答案1
而不是\j in {2,4,6,8}
你试图\j in {2.0,4.0,6.0,8.0}
定位0
锚点。
\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[font=\small,>=latex,
add/.style={draw=black,circle,inner sep=0pt},
branch/.style={fill=black,circle,minimum size=3pt,inner sep=0pt}%
]
\foreach \i in {2,4,6,8} {%
\node[add] at (-1,\i) (add\i) {$+$};
}
\foreach \i[evaluate={\j=int(\i+1)}] in {1,3,5,7} {%
\node[branch] at (-1,\i) (dot\i) {};
\draw[->] (dot\i) -- (add\j);
}
\end{tikzpicture}
\end{document}
或者更简单
\foreach \i/\j in {1/2,3/4,5/6,7/8} ...
答案2
\documentclass[ tikz,
border =5mm]{standalone}
\begin{document}
\begin{tikzpicture}[font=\small,>=latex,
add/.style={circle, draw=black, inner sep=0pt},
branch/.style={circle, fill=black, minimum size=3pt, inner sep=0pt,
node contents={} }%
]
\foreach \i in {0,2,4,6}
{%
\node (add\i) [add] at (-1,\i) {$+$};
\draw[->] (-1,\i-1) node[branch] -- (add\i);
}
\end{tikzpicture}
\end{document}
给出了期望的结果:-)