[Tex/LaTex] Creating a rainbow color macro

colortikz-pgf

I'm trying to draw a picture in tikz whose code is generated by another computer program. The program outputs hundreds of numbers in between 0 and 100, and I'd like to color objects in the picture on a spectrum according to the numbers.

For instance, suppose the spectrum I choose is red-orange-yellow-green-blue-violet. Then I would want to define a macro that has one input (a number between 0 and 100) and gives a color according to the following rules:

0=red

20=orange

40=yellow

60=green

80=blue

100=violet

Any number in between would be an appropriate mix. For example, 5 would be mostly red with a little bit of orange. 55 would be mostly green with a little bit of yellow.

Thank you in advance!

Best Answer

Nested use of \ifnum to define a color via \colorlet does the job:

enter image description here

Code:

\documentclass{article}    
\usepackage{xcolor}
\usepackage{pgffor}

\colorlet{MyColor}{black}%
\newcommand{\MixValue}{0}
\newcommand*{\SetColor}[1]{%
    \ifnum#1<21
        \pgfmathtruncatemacro{\MixValue}{100*#1/20}%
        \colorlet{MyColor}{orange!\MixValue!red}%
    \else
        \ifnum#1<41
            \pgfmathtruncatemacro{\MixValue}{100*(#1-20)/20}%
            \colorlet{MyColor}{yellow!\MixValue!orange}%
        \else
            \ifnum#1<61
                \pgfmathtruncatemacro{\MixValue}{100*(#1-40)/20}%
                \colorlet{MyColor}{green!\MixValue!yellow}%
            \else
                \ifnum#1<81
                    \pgfmathtruncatemacro{\MixValue}{100*(#1-60)/20}%
                    \colorlet{MyColor}{blue!\MixValue!green}%
                \else
                    \ifnum#1<101
                        \pgfmathtruncatemacro{\MixValue}{100*(#1-80)/20}%
                        \colorlet{MyColor}{violet!\MixValue!blue}%
                    \else
                    \fi%
                \fi%
           \fi%
       \fi%
    \fi%
}%

\newcommand*{\ShowInAppropriateColor}[1]{%
    \SetColor{#1}%
    \textcolor{MyColor}{#1}%
}%

\begin{document}
\noindent
\foreach \x in {0,...,100} {%
    \ShowInAppropriateColor{\x}
}%
\end{document}