Matplotlib: how to adjust the space between legendary markers and shortcuts?

I want to adjust the space between legend labels and shortcuts. Once the space is too large by default. Does anyone know how to do this?

Thanks.

+7
python matplotlib legend
source share
1 answer

legend() has kwarg in the name handletextpad , which will do what you are looking for. By default, this value is 0.8. From docs :

handletextpad : float or None

The strip between the legend handle and the text. Measured in unit font sizes.

The default value is None, which takes a value from legend.handletextpad rcParam .

So when you call legend , add this kwarg and experiment with the value. Something like:

 ax.legend(handletextpad=0.1) 

Consider the following:

 import matplotlib.pyplot as plt fig, (ax1, ax2) = plt.subplots(ncols=2) ax1.plot(range(5), 'ro', label='handletextpad=0.8') ax2.plot(range(5), 'bo', label='handletextpad=0.1') ax1.legend() ax2.legend(handletextpad=0.1) plt.show() 

enter image description here

+10
source share

All Articles