Drawing color tiles using Tikz

by skyphantasy   Last Updated July 11, 2019 21:23 PM

Hi good people of StackExchange, I want to draw a colored tile using Tikz. Roughly to represent the percentage three kind of things have in comparison to their total. The picture I want can be produced using the following.

\usepackage{tikz}

\newcommand\colorTiles[1]{
    \begin{tikzpicture}
      \draw[ultra thick](0,0) rectangle (1,0.5);
      \draw[fill = red](0, 0) rectangle (0.3, 0.5);
      \draw[fill = green](0.3, 0) rectangle (0.7, 0.5);
      \draw[fill = purple](0.7, 0) rectangle(1, 0.5);
    \end{tikzpicture}
 }

\colorTiles{}

enter image description here

Now my question is, how can I define the new command so that I don't have to adjust the proportions every time? Ideally, I just need to use

\colorTile{0.3, 0.5, 0.2}

And I should get a tile with 30% red, 50% green, and 20% purple. I'm not familiar with Tikz so please help me.

Thanks in advance!



Answers 1


Welcome to TeX-SE! The following produces such bars. The syntax is as simple as

\pic{color tile={0.3, 0.5, 0.2}};

The colors are stored in a list and can be adjusted, as illustrated in the following example. The width is stored in a pgf key and can also be adjusted.

\documentclass[tikz,border=3.14mm]{standalone}
\begin{document}
\begin{tikzpicture}[pics/color tile/.style={code={
 \path (0,0) coordinate (aux);
 \foreach \XX [count=\YY starting from 0] in {#1} 
 {\pgfmathsetmacro\mycol{{\LstCols}[\YY]}
 \draw[line width=\pgfkeysvalueof{/tikz/color tile/width},color=\mycol]
 (aux) -- ++(\XX,0) coordinate (aux);}
 \draw[thick] (0,-\pgfkeysvalueof{/tikz/color tile/width}/2) rectangle
 (aux|-0,\pgfkeysvalueof{/tikz/color tile/width}/2);
 }},color tile/.cd,width/.initial=5mm]
 \edef\LstCols{"red","green","purple","blue"} %< adjust and extent if needed
 \path pic{color tile={0.3, 0.5, 0.2}} (3,0) pic{color tile={0.3,0.6,0.4, 0.5}};
 \edef\LstCols{"orange","purple","yellow","red","blue"} %< adjusted and extended list
 \path  (1,-2) pic{color tile={0.3,0.6,0.4, 0.5,0.8}};
 \tikzset{color tile/width=1cm}
 \path  (1,-4) pic{color tile={0.3,0.6,0.4, 0.5,0.8}};
\end{tikzpicture}
\end{document}

enter image description here

marmot
marmot
July 11, 2019 20:44 PM

Related Questions


Updated December 18, 2018 02:23 AM

Updated March 30, 2018 22:23 PM

Updated November 20, 2018 12:23 PM

Updated April 14, 2017 04:23 AM

Updated June 04, 2019 16:23 PM