The following code draws a bar chart with number labels. I want the entries in the legend to be the other way around i.e. for there to be a gray box at the top with the label "two", and a white box below with the label "one". How can I do that? I could well be missing something obvious. EDIT: read on for a version using pgfplots 1.14
\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.3}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ybar stacked,
symbolic x coords={A,B,C},
xtick=data,
xticklabel style={align=center},
nodes near coords={\pgfmathprintnumber\pgfplotspointmeta},
nodes near coords align={vertical},
nodes near coords align={anchor=north},%Move values in bar
totals/.style={nodes near coords align={anchor=south}},
]
\addplot [fill=white] coordinates {
({A},24)
({B},16)
({C},11)};
\addlegendentry{one}
\addplot [fill=lightgray,point meta=explicit] coordinates {
({A},53)[53]
({B},47)[47]
({C},33)[33]};
\addlegendentry{two}
\addplot[totals] coordinates {
({A},0)
({B},0)
({C},0)};
\legend{one,two}
\end{axis}
\end{tikzpicture}
\end{document}
EDIT: for anyone who comes along later, the following code gets almost the same layout as my original post, but is compatible with version 1.14 of pgfplots (see tex.stackexchange.com/a/162389/95441). I've included the reverse legend
suggestion from Jake, which solves my original problem.
\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.14}
\begin{document}
\begin{tikzpicture}
\pgfplotsset{
show sum on top/.style={
/pgfplots/scatter/@post marker code/.append code={%
\node[
at={(normalized axis cs:%
\pgfkeysvalueof{/data point/x},%
\pgfkeysvalueof{/data point/y})%
},
anchor=south,
]
{\pgfmathprintnumber{\pgfkeysvalueof{/data point/y}}};
},
},
}
\begin{axis}[
reverse legend,
ybar stacked,
ymin=0,
ymax=90,
symbolic x coords={A,B,C},
xtick=data,
xticklabel style={align=center},
nodes near coords={\pgfmathprintnumber\pgfplotspointmeta},
]
\addplot [fill=white] coordinates {
({A},24)
({B},16)
({C},11)};
\addlegendentry{one}
\addplot [fill=lightgray,show sum on top] coordinates {
({A},53)
({B},47)
({C},33)};
\addlegendentry{two}
\legend{one,two}
\end{axis}
\end{tikzpicture}
\end{document}
Best Answer
Set
reverse legend
in theaxis options
, and addforget plot
to those\addplot
commands you don't want to appear in the legend. Also, you only need either the two\addlegendentry
commands, or the\legend
command, but not both.