无法读取 pgfplots 条形图的文本标签

无法读取 pgfplots 条形图的文本标签

我已经开始使用 pgfplots,可以绘制所有数据都是数字的散点图,但我对 xlabel 是文本的条形图却毫无办法。我尝试在手册和这里找到解决方案,但似乎都不起作用。我试图得到一个堆叠的 ybar,每个条形代表一个年度季度,条形由不同的贡献组成,但在绝望中,我很乐意只绘制第一列数据。以下是我得到的,但我收到错误,例如“索引为 1 的请求列表条目\datatable太大;此列表元素不足。”。有人能告诉我前进的方向吗?注释行也试过了。

\documentclass{article}
\usepackage{pgfplotstable}
\pgfplotsset{compat=1.9}

\begin{document}
\pgfplotstableread[col sep=comma]{
Year,Electricity,Stationary,Transport,Fugitive,Industrial,Agriculture,Waste
September2003,185.9,78.5,76.3,33.8,30.6,89.3,13.3
September2004,195.2,79.4,79.1,34.2,31.2,89.1,13.0
September2005,194.4,81.8,79.5,35.6,31.1,88.5,12.8
September2006,200.0,81.3,81.2,36.8,31.5,88.7,12.7
September2007,202.4,83.2,83.7,39.4,33.4,86.6,13.0
September2008,204.3,85.2,85.1,38.0,33.9,86.0,13.3
September2009,201.0,84.1,84.9,39.0,30.5,83.3,13.3
September2010,198.6,89.1,86.0,39.4,34.6,82.4,13.3
September2011,192.4,90.1,89.1,38.8,34.0,85.3,12.7
September2012,189.0,90.7,90.9,41.4,30.4,88.8,12.7
September2013,178.7,92.2,92.8,44.8,30.5,90.4,12.6
}\datatable;

\begin{tikzpicture}
\begin{axis}[
    ybar,
    ymin=0,
    ytick=data,
    symbolic x coords={year 1, year 2}, 
]
\addplot table[xticklabels from table]{\datatable}{Year};
%\addplot table[x expr=\thisrowno{0}, y expr=\thisrowno{1}*-1] {\datatable};
\end{axis}
\end{tikzpicture}%
\end{document}

答案1

这会是您想要的吗?要绘制堆叠的 ybar,请ybar用替换ybar stacked并添加更多addplot命令y=stationary,等等。还可以删除ymax=210或重置它。或者以更简洁的方式自动执行,如第二张图所示。

\foreach \i in {Electricity,Stationary,Transport,Fugitive,Industrial,Agriculture,Waste}{%
\addplot table [x expr=\coordindex, y=\i] {\datatable};}

在此处输入图片描述

在此处输入图片描述

代码:

\documentclass[border=2cm]{standalone}
\usepackage{pgfplotstable}
\pgfplotsset{compat=1.8}

\begin{document}

\pgfplotstableread[col sep=comma]{
Year,Electricity,Stationary,Transport,Fugitive,Industrial,Agriculture,Waste
September2003,185.9,78.5,76.3,33.8,30.6,89.3,13.3
September2004,195.2,79.4,79.1,34.2,31.2,89.1,13.0
September2005,194.4,81.8,79.5,35.6,31.1,88.5,12.8
September2006,200.0,81.3,81.2,36.8,31.5,88.7,12.7
September2007,202.4,83.2,83.7,39.4,33.4,86.6,13.0
September2008,204.3,85.2,85.1,38.0,33.9,86.0,13.3
September2009,201.0,84.1,84.9,39.0,30.5,83.3,13.3
September2010,198.6,89.1,86.0,39.4,34.6,82.4,13.3
September2011,192.4,90.1,89.1,38.8,34.0,85.3,12.7
September2012,189.0,90.7,90.9,41.4,30.4,88.8,12.7
September2013,178.7,92.2,92.8,44.8,30.5,90.4,12.6
}\datatable

\begin{tikzpicture}
\begin{axis}[
    ybar,
    ymin=0,
    ymax=210,
    xtick=data,
    xticklabels from table={\datatable}{Year},
    x tick label style={rotate=90, anchor=east}
%%symbolic x coords={year 1, year 2, year 3, year 4, year 5, year 6, year 7, year 8, year 9, year 10, year 11}, 
]
\addplot table [x expr=\coordindex, y=Electricity] {\datatable};  
\end{axis}
\end{tikzpicture}%
\end{document}

相关内容