我尝试做一些 TikZ 自动化并陷入以下示例:
\begin{tikzpicture}[line width=0.8, ->, scale = 1.5]
\tikzstyle{vertex}=[circle,fill=black!25,minimum size=17pt,inner sep=0pt]
\def \n {4}
\foreach \s in {1,...,\n}
{
\node[vertex] (\s)
at ({int(mod(\s - 1, 2)* 3) } , {int(-int((\s - 1) / 2) * 3))}) {$\s$};
}
\foreach[evaluate=\s as \ns using int({mod(\s, \n)+1})] \s in {1,...,\n}
{
\draw[] (\s) -- (\ns);
}
\end{tikzpicture}
其结果显示节点箭头穿过标签。我尝试手动执行此操作:
\begin{tikzpicture}[line width=0.8, ->, scale = 1.5]
\tikzstyle{vertex}=[circle,fill=black!25,minimum size=17pt,inner sep=0pt]
\foreach \name/\x/\y in {1/0/0, 2/1/0, 3/0/-1, 4/1/-1}
{
\node[vertex] (\name) at ({\x * 3}, {\y * 3}) {$\name$};
}
\foreach \from/\to in {1/2, 2/3, 3/4, 4/1}
{
\draw[] (\from) -- (\to);
}
\end{tikzpicture}
并且它正常工作(第一个是顶部代码,第二个是底部)。
差异从何而来?
答案1
你没有正确设置花括号。而不是
int({mod(\s, \n)+1})
你需要
{int(mod(\s, \n)+1)}
为了避免像这样的数字1.0
,它.0
会被解释为东锚点。
\documentclass[tikz,border=3.14mm]{standalone}
\begin{document}
\begin{tikzpicture}[line width=0.8, ->, scale = 1.5,
vertex/.style={circle,fill=black!25,minimum size=17pt,inner sep=0pt}]
\def \n {4}
\foreach \s in {1,...,\n}
{
\node[vertex] (\s)
at ({int(mod(\s - 1, 2)* 3) } , {int(-int((\s - 1) / 2) * 3))}) {$\s$};
}
\foreach[evaluate=\s as \ns using {int(mod(\s, \n)+1)}] \s in {1,...,\n}
{
\draw[] (\s) -- (\ns);
}
\end{tikzpicture}
\end{document}