3

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.

\begin{figure}[t]
    \textcolor{red}{\rule{5cm}{1mm}}
    \hspace{-.277cm}\textcolor{green}{\rule{5cm}{1mm}}
    \hspace{-.277cm}\textcolor{blue}{\rule{5cm}{1mm}}
\end{figure}

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
5

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?

\documentclass{article}
\usepackage{xcolor,etoolbox}

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

\newcommand{\coloredrulei}[3]{% {segment length}{rule height}{colors}
  \renewcommand*{\do}[1]{%
    \textcolor{##1}{\rule{#1}{#2}}}
  \begingroup\docsvlist{#3}\endgroup}

\newcommand{\coloredrule}[3]{% {total length}{rule height}{colors}
  \setlength{\colortotallength}{#1}
  \renewcommand*{\do}[1]{%
      \stepcounter{colorcounter}}
    \setcounter{colorcounter}{0}
    \docsvlist{#3}
  \setlength{\colorsegmentlength}{%
    \dimexpr \numexpr \colortotallength / \value{colorcounter} \relax sp \relax}
  \coloredrulei{\colorsegmentlength}{#2}{#3}}
\begin{document}

\coloredrule{20mm}{1cm}{red,orange,yellow,green,blue,violet}

\coloredrule{\textwidth}{2mm}{green,red,yellow,green,red,yellow,green,red,yellow}

\end{document}

enter image description here

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

| improve this answer | |
2

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

enter image description here

\documentclass[a4paper,12pt]{article}
\usepackage{tikz,xcolor}
\tikzset{every picture/.style={line width=3pt}}
\begin{document}

\begin{tikzpicture}[x=1pt,y=1pt,yscale=-5,xscale=5]
\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) ;
\end{tikzpicture}

\end{document}
| 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.