9

How can I create a TikZ/pgf-style that will put a coordinate, which should be named automatically, at each point of a path?

So the following code

\draw[put coordinates](0,0)--(3,2)--(4,7)--(-2,1);

Should be essentially the same as:

\draw(0,0)--(3,2)--(4,7)--(-2,1);
\coordinate(mypathcoordinate1) at (0,0);
\coordinate(mypathcoordinate2) at (3,2);
\coordinate(mypathcoordinate3) at (4,7);
\coordinate(mypathcoordinate4) at (-2,1);
2
  • Should this work for arbitrary paths (with curves and such), and do the paths have to remain closed?
    – Jake
    Commented Jun 28, 2013 at 12:40
  • Generally, the paths should be arbitrary. The coordinates should only lie at the explicitly given points, regardless of the way they are connected (line,move,curve,to,…). Acutely, I only work with -- or to and the paths are closed.
    – Toscho
    Commented Jun 28, 2013 at 13:56

1 Answer 1

9

You can use a show path construction decoration that you apply using a postaction to place the coordinates. That way, the underlying path is not changed at all.

Here's a style put coordinates that takes an optional argument to name the coordinates (default is coordinate):

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{decorations.pathreplacing}
\newcounter{coordinateindex}


\begin{document}
\tikzset{
    put coordinates/.style={
        initialize counter/.code={
            \setcounter{coordinateindex}{0}
        },
        initialize counter,
        decoration={
            show path construction,
            moveto code={
                \stepcounter{coordinateindex}
                \coordinate (#1\thecoordinateindex) at (\tikzinputsegmentfirst);
            },
            lineto code={
                \stepcounter{coordinateindex}
                \coordinate (#1\thecoordinateindex) at (\tikzinputsegmentlast);
            },
            curveto code={
                \stepcounter{coordinateindex}
                \coordinate (#1\thecoordinateindex) at (\tikzinputsegmentlast);
            },
            closepath code={
                \stepcounter{coordinateindex}
                \coordinate (#1\thecoordinateindex) at (\tikzinputsegmentlast);
            },
        },
        postaction={decorate}
    },
    put coordinates/.default=coordinate
}

\begin{tikzpicture}
\draw [put coordinates] (0,0) -- (3,2) to [out=90, in=0] (4,7)-- (-2,1);

\foreach \i in {1,...,\thecoordinateindex}{
    \fill (coordinate\i) circle [radius=2pt] node [above left] {\i};
}

\draw [red, put coordinates=secondpath] (0,1) -- (5,4) -- (4,1);
\foreach \i in {1,...,\thecoordinateindex}{
    \fill (secondpath\i) circle [radius=2pt] node [above left] {\i};
}
\end{tikzpicture}

\end{document}
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .