我正在尝试让 pgfplots 绘制一些像这样的条形图:
但我不知道如何pgfplots
添加第二个 X 轴标签,以便能够以易于阅读的方式绘制数据。我查看了手册,但找不到任何相关信息。我已经尝试解决这个问题很长时间了,但我无法让它工作。
有人能给我一个简单的例子来说明如何让它发挥作用吗?
答案1
这是我设法提出的解决方案。我使用了 Jakes 链接中的示例,它以应有的方式解决了问题。此外,使用表格时,我可以多次使用相同的轴标签,所以一切都很好。
\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\newcounter{groupcount}
\pgfplotsset{
draw group line/.style n args={5}{
after end axis/.append code={
\setcounter{groupcount}{0}
\pgfplotstableforeachcolumnelement{#1}\of\datatable\as\cell{%
\def\temp{#2}
\ifx\temp\cell
\ifnum\thegroupcount=0
\stepcounter{groupcount}
\pgfplotstablegetelem{\pgfplotstablerow}{[index]0}\of\datatable
\coordinate [yshift=#4] (startgroup) at (axis cs:\pgfplotsretval,0);
\else
\pgfplotstablegetelem{\pgfplotstablerow}{[index]0}\of\datatable
\coordinate [yshift=#4] (endgroup) at (axis cs:\pgfplotsretval,0);
\fi
\else
\ifnum\thegroupcount=1
\setcounter{groupcount}{0}
\draw [
shorten >=-#5,
shorten <=-#5
] (startgroup) -- node [anchor=north] {#3} (endgroup);
\fi
\fi
}
\ifnum\thegroupcount=1
\setcounter{groupcount}{0}
\draw [
shorten >=-#5,
shorten <=-#5
] (startgroup) -- node [anchor=north] {#3} (endgroup);
\fi
}
}
}
\pgfplotstableread{
1 15 4 1
2 13 3 1
3 18 5 2
4 10 1 2
}\datatable
\begin{document}
\makeatletter
\begin{tikzpicture}
\begin{axis}[
ylabel=label,
xtick=data,
xticklabels={x, y, x, y},
enlarge y limits=false,
enlarge x limits=0.1,
ymin=0,ymax=25,
ybar,
bar width=20pt,
legend style={
font=\footnotesize,
cells={anchor=west},
legend columns=5,
at={(0.5,-0.2)},
anchor=north,
/tikz/every even column/.append style={column sep=0.2cm}
},
draw group line={[index]3}{1}{a}{-3.5ex}{7pt},
draw group line={[index]3}{2}{b}{-3.5ex}{7pt},
]
\addplot+[error bars/.cd,y dir=both,y explicit] table[x index=0,y index=1,y error index=2] \datatable;
\end{axis}
\end{tikzpicture}
\end{document}