我在表中有一些数据;第一列有一些名称;第二列将“类别”与每个名称关联,第三列将“部分”与每个名称关联。所有条目均按字母顺序排列。
现在我想绘制一个简单的条形图,显示属于每个类别的名称总数的百分比。
我尝试过这个:
\documentclass{article}
\usepackage{pgfplotstable}
\usepackage{filecontents}
\pgfplotsset{compat=newest}
\begin{filecontents*}{test.txt}
{Name A} {Category One} {Section One}
{Name B} {Category Two} {Section Two}
{Name C} {Category One} {Section Two}
{Name D} {Category Two} {Section Three}
{Name E} {Category One} {Section One}
{Name F} {Category Three} {Section Three}
\end{filecontents*}
\pgfplotstableread[header=false]{test.txt}\mydata
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ybar,
width=16cm, height=10.5cm,
]
\addplot table[x expr=\coordindex1,y expr=\coordindex2]{\mydata};
\end{axis}
\end{tikzpicture}
\end{document}
但这给了我:
显然我误用了情节的规格。我应该怎么做才能获得所需的情节?
答案1
对于三种类型(或几种),这可以通过计数来快速完成;我制作了更多行来测试更多项目
\documentclass{standalone}
\usepackage{pgfplotstable,xstring}
\pgfplotsset{compat=1.10}
\pgfplotstableread[header=false]{
{Name A} {Category One}
{Name B} {Category Two}
{Name C} {Category One}
{Name D} {Category Two}
{Name E} {Category One}
{Name F} {Category Three}
{Name E} {Category One}
{Name F} {Category Three}
{Name E} {Category One}
{Name F} {Category Three}
{Name E} {Category One}
{Name F} {Category Three}
{Name D} {Category Three}
{Name D} {Category Two}
}\mydata
\def\mycollist{}
% Flatten 2nd col!
\pgfplotstableforeachcolumnelement{[index]1}\of\mydata\as\myentry{%
\edef\mycollist{\myentry,\mycollist}
}
% Count entries
\StrCount{\mycollist}{Category One}[\mycatone]
\StrCount{\mycollist}{Category Two}[\mycattwo]
\StrCount{\mycollist}{Category Three}[\mycatthree]
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ybar,ymin=0,
width=10cm, height=5.5cm,
xtick={1,2,3},
xticklabels={Category One,Category Two,Category Three}
]
\addplot coordinates {(1,\mycatone) (2,\mycattwo) (3,\mycatthree)};
\end{axis}
\end{tikzpicture}
\end{document}