[Tex/LaTex] PGFplots axis legend with multiple columns/rows of different lengths

legendpgfplots

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

Best Answer

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