How to align rows in matplotlib legend with 2 columns

You could set the handleheight keyword argument to a number which is just large enough that the height of the handle is larger than the space taken by the font. This makes the text appear aligned. Doing so may require to set the labelspacing to a small number, in order not to make the legend appear too big.

plt.legend(fontsize="xx-large", ncol=2,handleheight=2.4, labelspacing=0.05)

enter image description here

The drawback of this method, as can be seen in the picture, is that the lines shift upwards compared to the text’s baseline. It would probably depent on the usage case if this is acceptable or not.

In case it is not, one needs to dig a little deeper. The following subclasses HandlerLine2D (which is the Handler for Lines) in order to set a slightly different position to the lines. Depending on the total legend size, font size etc. one would need to adapt the number xx in the SymHandler class.

from matplotlib.legend_handler import HandlerLine2D
import matplotlib.lines

class SymHandler(HandlerLine2D):
    def create_artists(self, legend, orig_handle,xdescent, ydescent, width, height, fontsize, trans):
        xx= 0.6*height
        return super(SymHandler, self).create_artists(legend, orig_handle,xdescent, xx, width, height, fontsize, trans)

leg = plt.legend(handler_map={matplotlib.lines.Line2D: SymHandler()}, 
            fontsize="xx-large", ncol=2,handleheight=2.4, labelspacing=0.05) 

enter image description here

Leave a Comment