我有以下代码:
\begin{tikzpicture}
\pgfplotstableread{ % Read the data into a table macro
Label First Second Third
test 30 30 40
}\datatable
\begin{axis}[
xbar stacked, % Stacked horizontal bars
xmin=0, % Start x axis at 0
xmax = 100.01,
xticklabels={0, 0\%, 20\%,40\%,60\%,80\%,100\%},%
ytick=data, % Use as many tick labels as y coordinates
yticklabels from table={\datatable}{Label} % Get the labels from the Label column of the \datatable
]
\addplot [fill=yellow] table [x=First, y expr=\coordindex] {\datatable}; % Plot the "First" column against the data index
\addplot [fill=green!70!blue]table [x=Second, y expr=\coordindex] {\datatable};
\addplot [fill=red!80!yellow] table [x=Third, y expr=\coordindex] {\datatable};
\legend{test1, test2, test3}
\end{axis}
\end{tikzpicture}
有人可以解释一下为什么每个图例都没有显示“颜色框”并帮我添加它们吗?
如果我将条形图垂直化,它似乎可以工作,但我想让它保持水平。
非常感谢您的帮助!
答案1
这看起来像是 PGFPlots 中的一个错误:绘图类型legend image
的代码xbar stacked
定义不正确。如果您将以下代码片段放在序言中,图例将正确显示:
\pgfplotsset{
single xbar legend/.style={
legend image code/.code={\draw[##1,/tikz/.cd,bar width=6pt,bar shift=0pt,xbar] plot coordinates {(0.8em,0pt)};},
}
}