0

I just started learning python, so if the code isn't really appropriate, please let me know.

I got a fraction in a plot's legend. But since the position of the label didn't change, it looks quite weird: Plot example

My code concerning this plot is the following:

datalist = [(np.loadtxt(filename, skiprows=1), label) for filename,label in list_of_files]

for data, label in datalist:
pylab.errorbar(abs(data[:,0]), abs(data[:,3]), yerr = data[:,4], fmt = 'o', label=r'$\frac{U_1+U_2}{2}$')

legend = pylab.legend(loc = 2, numpoints = 1)
frame = legend.get_frame()
frame.set_facecolor('0.95')
pylab.xlabel(r'I$\,$[$\mathrm{\mu}$A]')
pylab.ylabel('U [V]')
pylab.ylim([0,0.1])
pylab.show()

I used the scope because there will be more values from different files in the plot, I just wanted to fix the label's position before adding the other data.

How can I change the position of the label in the legend?

loki
  • 9,816
  • 7
  • 56
  • 82
A.Kr
  • 1
  • 2
  • What is your `matplotlib` version? I do get the label centered correctly for 1.4.2 – taras Jun 20 '17 at 13:23
  • I have the matplotlib version 1.3.1. So maybe I should update it... – A.Kr Jun 20 '17 at 13:29
  • Possible duplicate of [Vertical alignment of matplotlib legend labels with LaTeX math](https://stackoverflow.com/questions/40424249/vertical-alignment-of-matplotlib-legend-labels-with-latex-math) – oliversm Mar 22 '19 at 10:51

1 Answers1

0

Maybe you can try something like the below. Found it on another answer on stackoverflow!

# Create legend
plt.plot(x, y, label = 'label_name')
leg = plt.legend( loc = 'upper right')

plt.draw() # Draw the figure so you can find the positon of the legend. 

# Get the bounding box of the original legend
bb = leg.get_bbox_to_anchor().inverse_transformed(ax.transAxes)

# Change to location of the legend. 
xOffset = 1.5
bb.x0 += xOffset
bb.x1 += xOffset
leg.set_bbox_to_anchor(bb, transform = ax.transAxes)


# Update the plot
plt.show()

Go here for more information: Move and resize legends-box in matplotlib