pgfplots легенда порядок

pgfplots легенда порядок

Следующий код рисует столбчатую диаграмму с числовыми метками. Я хочу, чтобы записи в легенде были наоборот, т. е. чтобы был серый ящик сверху с меткой "два" и белый ящик снизу с меткой "один". Как это сделать? Я вполне мог упустить что-то очевидное.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.

Чтобы игнорировать \addplots с помощью \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}

изображение, показывающее результат кода выше

Связанный контент