Python matplolib legend how to reduce distance between frame left edge and markers

Question:

As question suggests, I’m trying to reduce the distance between the left edge of the legend frame and the markers. enter image description here

In figure there is the current plot. I would like to find a way to:

  1. keeping the frameon = True in order to partially mask the underlying points;

  2. move markers and labels toward left reducing the distance between legend edge and markers

the actual legend configuration is the follow:

leg = ax.legend(handles=legend_elements, 
      fontsize=13, loc=(0.03, 0.01), frameon=True, 
      framealpha=0.5, handletextpad=-0.6, 
      labelspacing=0.08, borderpad=0)
Asked By: Giuseppe Angora

||

Answers:

You can try adding the following parameter and change the value as per your choice

handlelength=1

Example

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 3))
np.random.seed(10)

# WITHOUT handlelength
ax1.plot(np.random.randint(0, 10, 5), np.random.randint(0, 10, 5), 'bo', label='data1')
ax1.plot(np.random.randint(0, 10, 5), np.random.randint(0, 10, 5), 'rs', label='data2')
leg = ax1.legend(fontsize=19, loc=(0.03, 0.01), frameon=True, 
      framealpha=0.5, handletextpad=0.5, 
      labelspacing=0.08, borderpad=0.0)


# WITH handlelength
ax2.plot(np.random.randint(0, 10, 5), np.random.randint(0, 10, 5), 'bo', label='data1')
ax2.plot(np.random.randint(0, 10, 5), np.random.randint(0, 10, 5), 'rs', label='data2')
leg = ax2.legend(fontsize=19, loc=(0.03, 0.01), frameon=True, 
      framealpha=0.5, handletextpad=0.5, 
      labelspacing=0.08, borderpad=0.0, handlelength=1)

enter image description here

Answered By: Sheldore

Try using a negative value for borderpad. That will likely cause the legend to move downward as well, so adjust with borderaxespad.

Something like this:

leg = ax.legend( 
      fontsize=13, loc="lower left", frameon=True, 
      framealpha=1, handletextpad=-0.6, 
      labelspacing=0.08, borderpad=-0.5, borderaxespad=1)

Please note that rather than an absolute location, I used "lower left" for the legend location. Otherwise the whole “move stuff around with borderpad and borderaxspread” gets wonky (not a very precise explanation, I know:).

Answered By: Sinan Kurmus

Thanks to Sheldore and Sinan Kurmus, the solution was combining both your suggestions:

leg = ax.legend(handles=legend_elements, 
      fontsize=13, loc=(0.03, 0.01), frameon=True, 
      framealpha=0.5, handletextpad=0., 
      labelspacing=0.08, borderpad=0.,
      handlelength=1.2, borderaxespad=1)

I chose Sinan Kurmus’ answer as best to support his rank.


This answer was posted as an edit to the question Python matplolib legend how to reduce distance between frame left edge and markers by the OP Giuseppe Angora under CC BY-SA 4.0.

Answered By: vvvvv