2012-08-16 69 views
53

Desde actualizar matplotlib me sale el siguiente error cada vez que intenta crear una leyenda:Leyendas matplotlib no trabajar

/usr/lib/pymodules/python2.7/matplotlib/legend.py:610: UserWarning: Legend does not support [<matplotlib.lines.Line2D object at 0x3a30810>] 
Use proxy artist instead. 

http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist 

    warnings.warn("Legend does not support %s\nUse proxy artist instead.\n\nhttp://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist\n" % (str(orig_handle),)) 
/usr/lib/pymodules/python2.7/matplotlib/legend.py:610: UserWarning: Legend does not support [<matplotlib.lines.Line2D object at 0x3a30990>] 
Use proxy artist instead. 

http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist 

    warnings.warn("Legend does not support %s\nUse proxy artist instead.\n\nhttp://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist\n" % (str(orig_handle),)) 

Esto ocurre incluso con un guión trivial como esto:

import matplotlib.pyplot as plt 

a = [1,2,3] 
b = [4,5,6] 
c = [7,8,9] 

plot1 = plt.plot(a,b) 
plot2 = plt.plot(a,c) 

plt.legend([plot1,plot2],["plot 1", "plot 2"]) 
plt.show() 

tengo encontré el enlace que el error me indica que es bastante inútil para diagnosticar el origen del error.

Respuesta

107

Usted debe agregar comas:

plot1, = plt.plot(a,b) 
plot2, = plt.plot(a,c) 

La razón por la que necesita el comas es porque plt.plot() devuelve una tupla de objetos de línea, no importa cuántos realmente se crea a partir de la orden. Sin la coma, "plot1" y "plot2" son tuplas en lugar de objetos de línea, lo que hace que falle la última llamada a plt.legend().

La coma implícitamente descomprime los resultados de modo que en lugar de una tupla, "plot1" y "plot2" se convierten automáticamente en los primeros objetos dentro de la tupla, es decir, los objetos de línea que realmente desea.

http://matplotlib.sourceforge.net/users/legend_guide.html#adjusting-the-order-of-legend-items

line, = plot(x,sin(x)) what does comma stand for?

+7

que funcionaba, algo bastante arcano! –

+2

¿podría copiar/agregar la explicación aquí? stackoverflow fomenta la copia de piezas relevantes en el sitio (resaltado, archivado) – n611x007

5

Uso handles También conocido como Proxy artists

import matplotlib.lines as mlines 
import matplotlib.pyplot as plt 

blue_line = mlines.Line2D([], [], color='blue', label='My Label') 
reds_line = mlines.Line2D([], [], color='reds', label='My Othes') 

plt.legend(handles=[blue_line, reds_line]) 

plt.show() 
0

Usar la palabra clave "etiqueta", así:

pyplot.plot(x, y, label='x vs. y') 

y luego añadir la leyenda de este modo:

pyplot.legend() 

La leyenda retendrá propiedades de línea como el espesor, colores, etc.

enter image description here