我想使用这个乳胶模块(复制自这里)绘制条形图。
\newcounter{barcount}
% draw a bar chart
% param 1: width
% param 2: height
% param 3: border color
% param 4: label text color
% param 5: label bg color
% param 6: cat 1 color
\newenvironment{barchart}[8]{
\newcommand{\barwidth}{0.35}
\newcommand{\barsep}{0.2}
% param 1: overall percent
% param 2: label
% param 3: cat 1 percent
% param 4: cat 2 percent
% param 5: cat 3 percent
\newcommand{\baritem}[5]{
\pgfmathparse{##3+##4+##5}
\let\perc\pgfmathresult
\pgfmathparse{#2}
\let\barsize\pgfmathresult
\pgfmathparse{\barsize*##3/100}
\let\barone\pgfmathresult
\pgfmathparse{\barsize*##4/100}
\let\bartwo\pgfmathresult
\pgfmathparse{\barsize*##5/100}
\let\barthree\pgfmathresult
\pgfmathparse{(\barwidth*\thebarcount)+(\barsep*\thebarcount)}
\let\barx\pgfmathresult
\filldraw[fill=#6, draw=none] (0,-\barx) rectangle (\barone,-\barx-\barwidth);
\filldraw[fill=#7, draw=none] (\barone, -\barx) rectangle (\barone+\bartwo,-\barx-\barwidth);
\filldraw[fill=#8, draw=none] (\barone+\bartwo,-\barx ) rectangle (\barone+\bartwo+\barthree,-\barx-\barwidth);
\node [label=180:\colorbox{#5}{\textcolor{#4}{##2}}] at (0,-\barx-0.175) {};
\addtocounter{barcount}{1}
}
\begin{tikzpicture}
\setcounter{barcount}{0}
}
{\end{tikzpicture}}
它的用法如下:
\begin{barchart}{10}{16}{sectcol}{textcol}{sectcol}{maincol}{secondcol}{thirdcol}
\baritem{100}{Python}{20}{20}{0}
\end{barchart}
是否可以更改模块来实现这一点?
提前致谢
答案1
我建议使用 pgf 键,而不是使用具有最多 8 个强制参数的环境和宏。然后代码简化为
\begin{barchart}
\baritem{Python}{40/scipy,40/scikit-learn}
\baritem{R}{40/tidywise}
\baritem{Pft}{30/hibernate,30/sleep,40/eat}
\end{barchart}
但您仍然可以通过更改 pgf 键(其初始值或可选参数)来完全控制外观。以下是完整的 MWE(这是此网站上代码通常共享的方式):
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\newcounter{barcount}
\tikzset{barchart/.cd,y distance/.initial=3em,
bar height/.initial=2em,width/.initial=6cm,
bar text/.style={font=\sffamily,text depth=0.25em},
description/.style={font=\sffamily,text depth=0.25em},
colors/.initial={"orange!80","blue!40","red","green!70!black"}}
\newenvironment{barchart}[1][]{%
\tikzset{barchart/.cd,#1}%
\newcommand{\baritem}[2]{\stepcounter{barcount}%
\path (0,-\number\value{barcount}*\pgfkeysvalueof{/tikz/barchart/y distance})
coordinate (tmp) node[left=1ex,yshift=\pgfkeysvalueof{/tikz/barchart/bar
height}/2,/tikz/barchart/description]{##1};
\foreach \Percentage/\Text [count=\X starting from 0] in {##2}
{\pgfmathsetmacro{\mycolor}{{\pgfkeysvalueof{/tikz/barchart/colors}}[\X]}
\path[fill=\mycolor] (tmp) rectangle ++
({(\Percentage/100)*\pgfkeysvalueof{/tikz/barchart/width}},
\pgfkeysvalueof{/tikz/barchart/bar height})
node[midway,/tikz/barchart/bar text]{\Text};
\path (tmp) + ({(\Percentage/100)*\pgfkeysvalueof{/tikz/barchart/width}},0)
coordinate(tmp); }
}
\begin{tikzpicture}
\setcounter{barcount}{0}}
{\end{tikzpicture}}
\begin{document}
\begin{barchart}
\baritem{Python}{40/scipy,40/scikit-learn}
\baritem{R}{40/tidywise}
\baritem{Pft}{30/hibernate,30/sleep,40/eat}
\end{barchart}
\end{document}