![使用 Tikz 绘制彩色瓷砖](https://linux22.com/image/398632/%E4%BD%BF%E7%94%A8%20Tikz%20%E7%BB%98%E5%88%B6%E5%BD%A9%E8%89%B2%E7%93%B7%E7%A0%96.png)
大家好,StackExchange 的各位,我想用 Tikz 画一个彩色图块。大致表示三种事物相对于其总数的百分比。我想要的图片可以使用以下方法制作。
\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{}
现在我的问题是,我该如何定义新命令,以便不必每次都调整比例?理想情况下,我只需要使用
\colorTile{0.3, 0.5, 0.2}
我应该得到一个 30% 红色、50% 绿色和 20% 紫色的图块。我不熟悉 Tikz,所以请帮助我。
提前致谢!
答案1
欢迎使用 TeX-SE!下面生成这样的条形图。语法很简单,
\pic{color tile={0.3, 0.5, 0.2}};
颜色存储在列表中,可以调整,如下例所示。宽度存储在 pgf 键中,也可以调整。
\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}
至于您对命令的评论:这是一个提议。
\documentclass{article}
\usepackage{tikz}
\tikzset{pics/color tile/.style={code={
\edef\LstCols{\pgfkeysvalueof{/tikz/color tile/colors}}
\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=1em,
colors/.initial={"red","green","purple","blue"}}
\newcommand{\ColorTile}[2][]{\tikz{\pic[color tile/.cd,#1]{color tile={#2}};}}
\begin{document}
\begin{tabular}{ll}
\ColorTile{0.3, 0.5, 0.2} & ABC \\
\ColorTile{0.1, 0.2, 0.7} & UVW \\
\ColorTile[colors={"red","green","blue"}]{0.3, 0.5, 0.2} & XYZ\\
\end{tabular}
\end{document}
答案2
回答这个问题只是为了防止有人需要它:
\newcommand\colorTiles[3]{
\begin{tikzpicture}
\draw[ultra thick](0,0) rectangle (2,0.5);
\draw[fill = red](0, 0) rectangle (#1 * 2, 0.5);
\draw[fill = green](#1 * 2, 0) rectangle (#2 * 2 + #1 * 2, 0.5);
\draw[fill = purple](#2 * 2 + #1 * 2, 0) rectangle(#3 * 2 + #2 * 2 + #1 * 2, 0.5);
\draw[fill = gray](#3 * 2 + #2 * 2 + #1 * 2, 0) rectangle(2, 0.5);
\end{tikzpicture}
}
然后我们就可以将\colorTiles{0.2}{0.5}{0.1}
其内联。