1

My goal is to draw a line in different colors and not start a new line, so this produces a line and is working:

\documentclass[tikz=true,border=0pt]{standalone}
\begin{document}%
\begin{tikzpicture}[x=1mm, y=1mm]%
    \draw [line width=5mm, color=green] (0,0) -- +(5,0) {};
    \draw [line width=5mm, color=red] (5,0) -- +(5,0) {};
    \draw [line width=5mm, color=green] (10,0) -- +(5,0) {};
    \draw [line width=5mm, color=red] (15,0) -- +(5,0) {};
\end{tikzpicture}%
\end{document}

It would be nice not to start a new line...like this:

...
    \draw [line width=5mm, color=green] (0,0) -- +(5,0) -- [color=red] - +(5,0) -- [color=blue] - +(5,0) {};
...

Cannot find an approach. It is just to ease things a bit.

3
  • 1
    According to this webpage, you cannot change the color option along path, you have to split your path as you did in the first version of the code.
    – KersouMan
    Commented Oct 23, 2019 at 7:15
  • You could define a pic-style that is a line with varying colours, but behind the scenes it would still work using multiple paths.
    – Skillmon
    Commented Oct 23, 2019 at 7:17
  • All right - would be easier sometimes. Thank you.
    – texpiet
    Commented Oct 23, 2019 at 7:33

1 Answer 1

3

You can use postaction with dash pattern.

\documentclass[tikz=true,border=0pt]{standalone}
\begin{document}%
\begin{tikzpicture}[x=1mm, y=1mm]%
    \draw [line width=5mm, color=red,postaction={draw=green,dash pattern=on
    5mm off 5mm}] (0,0) -- +(20,0) {};
\end{tikzpicture}%
\end{document}

enter image description here

The white gaps at the end come from the requirement that the bounding box is also correct if you use line cap=rect. You need the larger bounding box if the path is not just a horizontal line since otherwise parts would get clipped away.

2
  • If you do not like these white gaps, use \documentclass[tikz=true,border=0pt]{standalone} \begin{document}% \begin{tikzpicture}[x=1mm, y=1mm]% \clip (0,-2.5) rectangle ++ (20,5); \draw [line width=5mm, color=red,postaction={draw=green,dash pattern=on 5mm off 5mm}] (0,0) -- +(20,0) {}; \end{tikzpicture}% \end{document}.
    – user194703
    Commented Oct 23, 2019 at 11:37
  • also a nice approach. thank you @Schrödinger's cat! This explains the gaps
    – texpiet
    Commented Oct 23, 2019 at 11:38

You must log in to answer this question.

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