[Tex/LaTex] How to draw path with alternating colors

drawtikz-pgf

I want to draw a path where edges have alternating colors, like:

enter image description here

Ideally I want to use

\draw[red] (3,0)-- (3.5,0.5) -- (4,0.2) -- (4,-0.2) -- (3.5,-0.5) -- cycle;

But this can only specify a single color for the entire path. The best I can do is to use \path below then I need to repeat every coordinate twice, which is very awkward. I was wondering

(a) if this can accomplished in the style \draw + cycle as above by specifying the color of each edge along the way.

(b) if somehow the operation of alternating color can be automated, that would be even better!

\documentclass{standalone}
\usepackage{tikz}
\begin{document}


\begin{tikzpicture}
\path 
(3,0) edge[blue] (3.5,0.5)
(3.5,0.5) edge[red] (4,0.2)
(4,0.2) edge[blue] (4,-0.2)
(4,-0.2) edge[red] (3.5,-0.5)
(3.5,-0.5) edge[blue] (3,0);
\end{tikzpicture}
\end{document}

Best Answer

You can use "append after command" to automatically repeat the coordinate. When you use edge tikz stores the target in \tikztotarget, but this is in a local scope. By the time the "append after command" code is executed, the most recent coordinate has been forgotten. So the every edge code has to store the current value of \tikztotarget in a global variable, using \global\let\currenttarget\tikztotarget. Then we can append this using append after command.

In order to automatically alternate color, we use the standard tex "command that alternates between doing two things" pattern, but again because of scope issues you have to remember to do a global assignment.

For reference the relevant command is \tikz@do@edge which is defined on line 2912 of tikz.code.tex. The edge is drawn on line 2932 and our edge style code is evaluated there, the append after command code gets locally stored in \tikz@after@path and is globally put into \tikz@after@path@smuggle on line 2933. The scope then ends and the \tikz@after@path@smuggle code is evaluated on line 2949.

\documentclass{article}
\usepackage{tikz}

\begin{document}
\def\alternatecolorred{%
    \pgfkeysalso{red}%
    \global\let\alternatecolor\alternatecolorblue % next time make it blue
}
\def\alternatecolorblue{%
    \pgfkeysalso{blue}%
    \global\let\alternatecolor\alternatecolorred % next time make it red
}
\let\alternatecolor\alternatecolorred % first coordinate is red
\begin{tikzpicture}[every edge/.append code = {%
    \global\let\currenttarget\tikztotarget % save \tikztotarget in a global variable
    \pgfkeysalso{append after command={(\currenttarget)}}% automatically repeat it
    \alternatecolor
}]

\draw (3,0) edge (3.5,0.5) edge (4,0.2) edge (4,-0.2) edge (3.5,-0.5) edge (3,0);
\end{tikzpicture}
\end{document}