I have a string "Line2D" appended in the beginning of my matplotlib legend. How to get rid of it? A simple python script that reproduces this problem is as follows:
import numpy as np
import matplotlib.pylab as plt
x=np.linspace(0,1,20)
y=np.sin(2*x)
z=np.cos(2*x)
p1, = plt.plot(x,y, label='sin(x)')
p2, = plt.plot(x,z, label='cos(x)')
plt.legend([p1, p2])
plt.show()
I get a figure in which I want to get rid of the extra string "Line2D" in the legend. I do not have enough reputation to post images. I was using anaconda python if that matters. Thanks for your help!
If you pass just one list to legend, it has to be the labels you want to show, not the objects whose labels you want to show.  It is converting those line objects to strings, which gives Line2D(...).
Since you gave the lines labels when you created them, you don't need to pass anything to legend.  Just plt.legend() will automatically use the labels you provided.
You can use plt.legend(handles=[p1, p2]).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With