close

How to align rows in matplotlib legend with 2 columns

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to align rows in matplotlib legend with 2 columns in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to align rows in matplotlib legend with 2 columns?

  1. How to align rows in matplotlib legend with 2 columns?

    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.

  2. align rows in matplotlib legend with 2 columns

    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.

Method 1

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

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read