
Следующий код рисует столбчатую диаграмму с числовыми метками. Я хочу, чтобы записи в легенде были наоборот, т. е. чтобы был серый ящик сверху с меткой "два" и белый ящик снизу с меткой "один". Как это сделать? Я вполне мог упустить что-то очевидное.EDIT: читайте дальше для версии с использованием 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}
РЕДАКТИРОВАТЬ:для тех, кто зайдет позже, следующий код имеет почти такую же структуру, как и мой исходный пост, но совместим с версией 1.14 pgfplots (см.tex.stackexchange.com/a/162389/95441). Я включил reverse legend
предложение Джейка, которое решает мою изначальную проблему.
\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}
решение1
Установите reverse legend
в axis options
, и добавьте forget plot
к тем \addplot
командам, которые вы не хотите видеть в легенде. Также вам нужны только либо две \addlegendentry
команды, либо \legend
команда, но не обе.
\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.3}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ybar stacked,
reverse legend,
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, forget plot] coordinates {
({A},0)
({B},0)
({C},0)};
\end{axis}
\end{tikzpicture}
\end{document}
решение2
Как Джейк уже сказал вего ответальтернативой было бы использование \legend
команды. Это имеет то преимущество, что не нужно использовать forget plot
команду \addplot
, которая помимо того, что не добавляет сюжет к легенде, имеет некоторые другие (возможно/иногда нежелательные) "побочные эффекты", такие как не продвижение cycle list
.
Чтобы игнорировать \addplot
s с помощью \legend
команды, просто напишите для них пустые метки.
(Кстати: когда даны оба, ie \addlegendentry
и , «выигрывает».)\legend
\legend
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.3}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ybar stacked,
reverse legend,
symbolic x coords={A,B,C},
xtick=data,
nodes near coords,
nodes near coords align={anchor=north},%Move values in bar
totals/.style={
nodes near coords align={anchor=south},
red, % <-- added, to distinguish it from "one"
},
]
\addplot [fill=white] coordinates {
(A,24) (B,16) (C,11)
};
\addplot [fill=lightgray,point meta=explicit] coordinates {
(A,53)[53] (B,47)[47] (C,33)[33]
};
\addplot [totals] coordinates {
(A,0) (B,0) (C,0)
};
% give all the `\addplot's that should not be shown in the legend
% an empty legend entry
% (here "three" is empty, because there is a comma after the last entry)
\legend{
one,
two,
}
% % perhaps this one easier to understand
% % (here "two" isn't shown in the legend
% \legend{
% one,
% ,
% three
% }
\end{axis}
\end{tikzpicture}
\end{document}