我想使用水平条形图比较两个不同年份的百分比。
这两个年份(1996 年和 2011 年)的值是通过 pgfplots 表给出的。我希望 1996 年的值显示在相应的 2011 年值的顶部。但是,当按正确的顺序添加它们时,图例条目的顺序却相反(先显示 2011 年,然后显示 1996 年)。
梅威瑟:
\documentclass[a4paper,11pt,twoside]{memoir}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\begin{document}
\pgfplotstableread[col sep=comma,header=true]{
Type,1996,2011
type1,41.26,46.57
type2,55.42,38.76
type3,0.14,0.11
type4,0.24,0.05
type5,0.79,13.20
type6,2.14,1.31
}\data
\begin{figure} [tb]%
\centering
\begin{tikzpicture}
\begin{axis}[
width=12cm,
xbar,
xtick={0,10,20,...,100},
xmin=0,
xmax=100,
grid=major,
nodes near coords, nodes near coords align={horizontal},
symbolic y coords={type6,type5,type4,type3,type2,type1},
ylabel={Type},
xlabel={Percentage},
y label style={at={(-0.1,0.5)}},
enlarge x limits={abs=0}
]
\addplot table [x=1996, y=Type] {\data};
\addplot table [x=2011, y=Type] {\data};
\legend{1996,2011}
\end{axis}
\end{tikzpicture}
\label{fig:distribution}
\end{figure}
\end{document}
我尝试手动更改图例顺序,如下所述这个帖子,但这导致图例中的条形图和文本之间的垂直对齐变得丑陋:
\documentclass[a4paper,11pt,twoside]{memoir}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\begin{document}
\pgfplotstableread[col sep=comma,header=true]{
Type,1996,2011
type1,41.26,46.57
type2,55.42,38.76
type3,0.14,0.11
type4,0.24,0.05
type5,0.79,13.20
type6,2.14,1.31
}\data
\begin{figure} [tb]%
\centering
\begin{tikzpicture}
\begin{axis}[
width=12cm,
xbar,
xtick={0,10,20,...,100},
xmin=0,
xmax=100,
grid=major,
nodes near coords, nodes near coords align={horizontal},
symbolic y coords={type6,type5,type4,type3,type2,type1},
ylabel={Type},
xlabel={Percentage},
y label style={at={(-0.1,0.5)}},
enlarge x limits={abs=0},
extra description/.code={
\matrix[/pgfplots/every axis legend]
{
\ref{1996} \pgfmatrixnextcell \node{1996};\\
\ref{2011} \pgfmatrixnextcell \node{2011};\\
};
}
]
\addplot table [x=2011, y=Type] {\data};
\label{2011}
\addplot table [x=1996, y=Type] {\data};
\label{1996}
\end{axis}
\end{tikzpicture}
\label{fig:distribution}
\end{figure}
\end{document}
正如帖子中建议的那样,我查阅了tikz
手册,但没有找到解决此问题的方法(至少对于我的乳胶技能而言)。有什么提示吗?
答案1
有一些键reverse legend
可以精确地执行您想要的操作。
将其添加到选项列表中会产生
\documentclass[a4paper,11pt,twoside]{memoir}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\begin{document}
\thispagestyle{empty}
\pgfplotstableread[col sep=comma,header=true]{
Type,1996,2011
type1,41.26,46.57
type2,55.42,38.76
type3,0.14,0.11
type4,0.24,0.05
type5,0.79,13.20
type6,2.14,1.31
}\data
\begin{figure} [tb]%
\centering
\begin{tikzpicture}
\begin{axis}[
width=12cm,
xbar,
xtick={0,10,20,...,100},
xmin=0,
xmax=100,
grid=major,
nodes near coords, nodes near coords align={horizontal},
symbolic y coords={type6,type5,type4,type3,type2,type1},
ylabel={Type},
xlabel={Percentage},
y label style={at={(-0.1,0.5)}},
enlarge x limits={abs=0},
reverse legend,
]
\addplot table [x=2011, y=Type] {\data};
\addplot table [x=1996, y=Type] {\data};
\legend{2011,1996}
\end{axis}
\end{tikzpicture}
\label{fig:distribution}
\end{figure}
\end{document}