Change the space between labels and lines of the legend in Python Matplotlib.pyplot


The result is:

Legend with changing padding between line and label using handletextpad option

This page how to change the space between the lines in legend and their labels.
By adding the option "handletextpad", you can increase or decrease the padding between handle and text of the legend labels.


In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
In [2]:
x = [1,2,3,4]
y1 = [1,2,3,4]
y2 = [2,3,4,5]
y3 = [4,3,2,1]
y4 = [5,4,3,2]
In [3]:
pads = [0.0,0.5,1.0,1.5]
fig = plt.figure(figsize=(5,5),facecolor='w')
for i,pad in zip(range(4),pads):
    ax = fig.add_subplot(2,2,i+1)
    ax.plot(x,y1,color='r',label='y1')
    ax.plot(x,y2,color='g',label='y2')
    ax.plot(x,y3,color='b',label='y3')
    ax.plot(x,y4,color='k',label='y4')
    # Draw legend with a option "handletextpad=pad".
    # handletextpad means the padding between the legend handle and text.
    # Measured in font-size units. 
    ax.legend(handletextpad=pad)
plt.savefig('change_handletextpad.png',dpi=200,bbox_inches='tight',pad_inches=0.05)
plt.show()