我想加载一个 ybar 堆叠图的 csv。该怎么做?这是一个最小示例,其中包括要在图表中使用的示例文件内容:
\documentclass{article}
\usepackage{xcolor}
\usepackage{pgfplots}
\usepackage{filecontents}
\begin{document}
\begin{filecontents}{data.csv}
Size A B C
X 30 30 47
Y 1 2 3
Z 69 68 50
\end{filecontents}
\begin{tikzpicture}
\begin{axis}[
ybar stacked,
bar width = 1cm,
enlargelimits=0.15,
legend style={at={(0.5,-0.40)},
anchor=north,legend columns=-1},
ylabel={\%-Anteile},
symbolic x coords={A, B, C},
xtick=data,
x tick label style={rotate=45,anchor=east,yshift=-0.3cm},
yticklabel={\pgfmathparse{\tick}\pgfmathprintnumber{\pgfmathresult}\%}
]
\addplot+[ybar] plot coordinates {(A,30) (B,30) (C,47)};
\addplot+[ybar] plot coordinates {(A,1) (B,2) (C,3)};
\addplot+[ybar] plot coordinates {(A,69) (B,68) (C,50)};
\legend{X, Y, Z}
\end{axis}
\end{tikzpicture}
\end{document}
答案1
您可以将文本文件加载到pgfplotstable
表格中,然后转置它。然后您只需执行\addplot table[x=Size,y=X] {\transposedtable};
。添加三个单独的s,或使用循环,如下例所示。当您在选项中有或时,\addplot
您不需要将选项添加ybar
到 every 。\addplot
ybar
ybar stacked
axis
无关评论:
xcolor
已由 加载tikz
,而 又由 加载pgfplots
,因此您实际上不必显式加载它。 的语法\addplot
是\addplot coordinates
,而不是\addplot plot coordinates
。(哪个教程教过这个?)
\documentclass{article}
%\usepackage{xcolor} %loaded by pgfplots
\usepackage{pgfplotstable} % also loads pgfplots
\usepackage{filecontents}
\begin{filecontents}{data.csv}
Size A B C
X 30 30 47
Y 1 2 3
Z 69 68 50
\end{filecontents}
\pgfplotstableread{data.csv}\mydata
% transpose table
\pgfplotstabletranspose[
% use first column as header
colnames from=Size,
% first cell/first row is changed to "colnames", change back to "Size"
input colnames to=Size]\transposeddata\mydata
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ybar stacked,
bar width = 1cm,
enlargelimits=0.15,
legend style={at={(0.5,-0.15)}, % changed -0.40 to =0.15
anchor=north,legend columns=-1},
ylabel={\%-Anteile},
symbolic x coords={A, B, C},
xtick=data,
x tick label style={rotate=45,anchor=east,yshift=-0.3cm},
yticklabel={\pgfmathparse{\tick}\pgfmathprintnumber{\pgfmathresult}\%}
]
\pgfplotsinvokeforeach{X,Y,Z}{ %loop over the three columns
\addplot table[x=Size,y=#1] {\transposeddata};
}
\legend{X, Y, Z}
\end{axis}
\end{tikzpicture}
\end{document}