# edges on graph do not align with center of nodes in foreach

As far as I can understand this should draw the same set of five edges in exactly the same way. The first set of edges are positioned correctly. But the second set of edges is horribly aligned. On my screen, of the \foreach edges, the bottom horizontal one is shifted to the right, the others seems to start ok and then end up further from the center of the pentagon then they should.

Aside from wondering how to fix the alignment, I would also love to understand why this only happens inside a \foreach.

I can "solve" this by first drawing the nodes with minimum size=0mm, and then at the very end redrawing them with 2mm, but that seems less than optimal...

\documentclass{beamer}

\usepackage{calc,ifthen}
\usepackage{amsthm,amsmath,amssymb}
\usepackage{tikz}

\begin{document}

\frame{
\begin{tikzpicture}
\def\r{2cm}

\foreach \t in {0,...,4} {
\node[circle,draw, outer sep=0mm, inner sep=0mm, minimum size=2mm] (a\t) at ({90+\t*72}:\r) {} ;
}

% draw the edges of the pentagon in a silly way
% draws edges from node-center to node-center
\draw (a0) edge (a1) ;
\draw (a1) edge (a2) ;
\draw (a2) edge (a3) ;
\draw (a3) edge (a4) ;
\draw (a4) edge (a0) ;

% draw the edges of the pentagon in a better way
% draws edges from node-something to node-something-else
\foreach \t in {0,...,4} {
\pgfmathsetmacro{\s}{mod(\t+1,5)}
\draw (a\t) edge (a\s) ;
}

\end{tikzpicture}
}

\end{document}


The problem is that

\pgfmathsetmacro{\s}{mod(\t+1,5)}


returns values for \s of 0.0, 1.0 etc. and not 0, 1 and so on. So, when you ask for a path to a\s, you are asking for a path to the point on the relevant node's border at an angle of 0 because this is what the anchor .0 means. If \s is rewritten to return merely the nodes' names without the .0 anchor, the correct result is obtained.

\pgfmathsetmacro{\s}{int(mod(\t+1,5))}


The lines in red show the second construction method perfectly corresponds with the first.

Note, however, that

\foreach \t [count=\s] in ...


is a lot simpler.

Complete (non-simple) code:

\documentclass[tikz,border=10pt,multi]{standalone}
\begin{document}
\begin{tikzpicture}
\def\r{2cm}
\foreach \t in {0,...,4} {
\node[circle,draw, outer sep=0mm, inner sep=0mm, minimum size=2mm] (a\t) at ({90+\t*72}:\r) {} ;
}

% draw the edges of the pentagon in a silly way
% draws edges from node-center to node-center
\draw (a0) edge (a1) ;
\draw (a1) edge (a2) ;
\draw (a2) edge (a3) ;
\draw (a3) edge (a4) ;
\draw (a4) edge (a0) ;

% draw the edges of the pentagon in a better way
% draws edges from node-something to node-something-else
\foreach \t in {0,...,4} {
\pgfmathsetmacro{\s}{int(mod(\t+1,5))}
\draw [red] (a\t) edge (a\s)  ;
}
\end{tikzpicture}
\end{document}

• That works perfectly, I forgot about the decimals. The count is a nice trick, I now have \foreach \t [count=\s] in {5,1,2,...,4}. – mike newman May 25 '16 at 3:07