Is there a way to draw a horizontal line with sections of different color and each section of identical length?

The code below will produce the result I'm looking for, but it's not an elegant way to do it.


Ideally, I want to create the line with relative lengths and be able to colorize it without the need of patching together three single lines.

  • 4
    Off-topic: If you would put a % sign at the end of lines, you wouldn't need to use the negative hspace. – Johannes_B May 1 '18 at 10:10

Something like this, which produces a \coloredrule command which takes a total length for the rule, and a width, and a comma separated list of colors?


\newlength{\colorsegmentlength}% Used internally
\newlength{\colortotallength}% Used internally
\newcounter{colorcounter}% Used internally

\newcommand{\coloredrulei}[3]{% {segment length}{rule height}{colors}

\newcommand{\coloredrule}[3]{% {total length}{rule height}{colors}
    \dimexpr \numexpr \colortotallength / \value{colorcounter} \relax sp \relax}




enter image description here

(With grateful acknowledgement to this answer for division of the lengths.)

| improve this answer | |

This code is simple...but it works! With line width=3pt you can increase the thickness of the line.

enter image description here

\tikzset{every picture/.style={line width=3pt}}

\draw [color=cyan]  (0,0) -- (5,0) ;
\draw [color=magenta]  (5,0) -- (10,0) ;
\draw [color=brown]  (10,0) -- (15,0) ;
\draw [color=green]   (15,0) -- (20,0) ;
\draw [color=red]   (20,0) -- (25,0) ;
\draw [color=yellow]   (25,0) -- (30,0) ;
\draw [color=red]   (30,0) -- (35,0) ;

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.