2

I want to add some spacing between the end of the legend entry and the legend border. I've tried using the arguments for pyplot.legend but I haven't found a combination that works. Here's a minimal working example:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0.0,1.0,10)
y = x

fig = plt.figure()
p, = plt.plot(x,y,'-o')
plt.legend([p],['$y = x$'], loc='best')
plt.show()

I've tried

plt.legend([p],['$y = x\/$'], loc='best')
plt.legend([p],['$y = x{ }$'], loc='best')
plt.legend([p],['$y = x\:$'], loc='best')
plt.legend([p],['$y = x$ '], loc='best')

But none of them work. It seems pyplot is too smart and removes any trailing whitespace. Is there any way to accomplish this?

To give you an example of why I want this, it's to balance out space on both sides with using one marker instead of two in the legend, see example below. The space beside the W-Y and Exp. is much smaller than the space on the left.

enter image description here

Blink
  • 1,444
  • 5
  • 17
  • 25

1 Answers1

1

I think you can get what you want with a combination of the kwargs borderpad and handletextpad.

(doc)

tacaswell
  • 84,579
  • 22
  • 210
  • 199
  • That could work; however, `borderpad` adds padding all the way around. Which then requires the use of `handletextheight` and `labelspacing`, on top of `handletextpad`. I was really hoping there would just be an easy fix to add a whitespace character at the end of an entry. – Blink May 14 '13 at 15:28
  • @William The legend code in rather complex with lots of nooks and carnies, there could very will be a parameter to tune _exactly_ what you want that I do not know about. It might be worth some time digging around in the code. What version of mpl are you using? – tacaswell May 14 '13 at 16:30
  • @William There is the snarky solution of turning the legend frame off so you can't tell ;) I would specifically look at how the bounding box is generated, I think that the point artists is much wider than it looks which is what gives you that extra padding. – tacaswell May 14 '13 at 16:32
  • I managed to get it to work (through brute-force trial-and-error). I just used the legend `kwargs` in the end. Interestingly enough, if you don't change `numpoints = 1`, you can just add space to the end, such as `plt.legend([p],['$y = x$ '])`, and it works. If you reduce `numpoints` to 1, then the space no longer works. – Blink May 14 '13 at 18:34