5

I have an axis environment in PGFplots with multiple graphs which correspond to certain group of data types. I want to stress this distinction by grouping the legend entries. In particular, using a legend with multiple columns. However, the different groups do not each have the same number of graphs, which would result in multiple columns of different lenghts in the legend. But how do I do this in PGFplots?

For example, how do I get a legend like

1 3 4
2   5

1 Answer 1

8

This can be done by using the commands \addlegendimage{empty legend} and \addlegendentry{}.

You have 5 graphs divided among 3 groups and the legend numbering increases in the vertical direction. Try

\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
    \begin{tikzpicture}
        \begin{axis}[legend columns=2,transpose legend]
            \addplot[domain=0:1] {x};\addlegendentry{1};
            \addplot[domain=0:1] {x^2};\addlegendentry{2};
            \addplot[domain=0:1] {x^3};\addlegendentry{3};

            % Add empty legend to fix the legend layout.
            \addlegendimage{empty legend}
            \addlegendentry{}

            \addplot[domain=0:1] {x^4};\addlegendentry{4};
            \addplot[domain=0:1] {x^5};\addlegendentry{5};          
        \end{axis}
    \end{tikzpicture}
\end{document}

For multiple legend rows of different lengths, the trick is similar. Simply use the empty legend entries, possibly in combination with transpose legend.

The result looks like

5
  • Nice! Could you add an image showing the output of the code?
    – Jake
    Mar 23, 2015 at 14:39
  • 2
    @Jake Yes, I just added a picture for the sake of completeness.
    – Adriaan
    Mar 23, 2015 at 15:03
  • Nice solution! I would like to do something similar (essentially a two-column transposed legend with four entries on the right and three entries on the left side). The problem is that I use a for loop to include the plots, so sneaking in an empty legend entry is not so easy here. Is there another possibility? Mar 31, 2016 at 19:22
  • @riddleculous Can't you split the for loop or add an if statement within the for loop to add the \addlegendentry{}?
    – Adriaan
    Apr 1, 2016 at 14:11
  • @Adriaan: An if statement would be a bit ugly since it will shift the iteration index by one. But splitting the for loop is much nicer in my case. I didn't think of this, thanks for suggesting it! Apr 1, 2016 at 14:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.