在矩形内绘制多条彩色线条

在矩形内绘制多条彩色线条

我想在一个矩形内绘制多条彩色短线。我发现了以下代码绘制彩色线条。我不确定如何绘制多条线条,这是我迄今为止最好的尝试:

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

\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}

\tikzstyle{box} = [rectangle, rounded corners, minimum width=4cm, minimum height=3cm,text centered, draw=black, fill=grey!10]

\begin{tikzpicture}
  \node [box] (population) {};
  \node [anchor=north] at (population.north) {Population};
  \node [anchor=south west] at (population.south west) {$\coloredrule{5mm}{1mm}{green}$}
\end{tikzpicture}

\end{document}

在此处输入图片描述

答案1

如果您命名了第一行(例如line1),您可以将接下来的几行放在它上面(然后依次依次放在每行上面)。

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

\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}

\tikzstyle{box} = [rectangle, rounded corners, minimum width=4cm, minimum height=3cm,text centered, draw=black, fill=gray!10]

\begin{tikzpicture}
  \node [box] (population) {};
  \node [anchor=north] at (population.north) {Population};
  
  \node (line1) [anchor=south west] at (population.south west) {$\coloredrule{5mm}{1mm}{green}$};    
  \node (line2) [anchor=south west] at (line1.north west) {$\coloredrule{10mm}{1mm}{blue}$};
  \node (line3) [anchor=south west] at (line2.north west) {$\coloredrule{8mm}{1mm}{red}$};
  \node (line4) [anchor=south west] at (line3.north west) {$\coloredrule{20mm}{1mm}{black}$};
  \node (line5) [anchor=south west] at (line4.north west) {$\coloredrule{16mm}{1mm}{yellow}$};
\end{tikzpicture}

\end{document}

您将获得以下输出:

在此处输入图片描述

(另请注意,您的 MWE 中有一个拼写错误,应该是“gray”而不是“grey”)

相关内容