# PGFplots axis legend with multiple columns/rows of different lengths

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


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]

% Add empty legend to fix the legend layout.

\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

• Nice! Could you add an image showing the output of the code?
– Jake
Mar 23, 2015 at 14:39
• @Jake Yes, I just added a picture for the sake of completeness. 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{}? 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