Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove extra string "Line2D" in matplotlib legend

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!

like image 824
Corrupted MyStack Avatar asked Oct 22 '14 03:10

Corrupted MyStack


2 Answers

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.

like image 64
BrenBarn Avatar answered Sep 24 '22 00:09

BrenBarn


You can use plt.legend(handles=[p1, p2]).

like image 26
Ludovic Trottier Avatar answered Sep 22 '22 00:09

Ludovic Trottier