TikZ-PGF – Using the Cycle Option When Drawing Between Nodes

tikz-pgf

Cycle lets you close curves when drawing, and

\coordinate (a) at (0,0);
\coordinate (b) at (1,0);
\coordinate (c) at (0.5, -1);
\draw (a) -- (b) -- (c) -- cycle;

works fine. Shouldn't also

\node (a) at (0,0) {};
\node (b) at (1,0) {};
\node (c) at (0.5, -1) {};
\draw (a) -- (b) -- (c) -- cycle;

give the same result?

The former gives a triangle, while the second doesn't close up. Is this a bug or am I missing something regarding the cycle option?

(Of course, as a workaround I could use the coordinates to draw the cycled path, and then draw the nodes at the same coordinates, but still…)

Best Answer

When you specify a bare node as a coordinate, as in (a), then TikZ tries to be helpful and interpret that as the most appropriate target on a. Most of the time, this is exactly what you want: \tikz \draw[->] (0,0) node (a) {A} (1,0) node (b) {B} (a) -- (b); typesets A → B, with the arrow starting a little to the right of the A and ending a little to the left of the B.

However, when doing a "cycle", you don't want that behaviour. You want the lines to join up. Even empty nodes have size, unless you explicitly tell them not to. So you need to override this "helpfulness" which is done by specifying which target you mean. Thus:

\node (a) at (0,0) {};
\node (b) at (1,0) {};
\node (c) at (0.5, -1) {};
\draw (a.center) -- (b.center) -- (c.center) -- cycle;

does what you want it to.

There are other ways to do this, in particular as your nodes are empty you could force them to have zero size. Indeed, \coordinate is actually a shorthand for \node[coordinate] and the special shape coordinate has empty size. So your first example, which works, is actually a special case of the second where the nodes are fiddled to be "point masses".