2012-08-16 56 views
53

自从升级matplotlib我得到每当试图创造一个传奇以下错误:Matplotlib传奇不工作

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() 

我有:

/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),)) 

这甚至有这样一个简单的脚本发生发现错误指向的链接在诊断错误来源时非常没用。

回答

107

您应该添加逗号:

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

您需要的逗号的原因是plt.plot()返回行对象的元组无论有多少实际上是从命令创建的。如果没有逗号,“plot1”和“plot2”就是元组而不是线对象,从而导致后续对plt.legend()的调用失败。

逗号隐式地解包结果,以便代替“tuple”,“plot1”和“plot2”自动成为元组中第一个对象,即您实际需要的线对象。

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

这工作,很神秘的东西! – 2012-08-16 08:28:08

+2

你可以在这里复制/添加解释吗? stackoverflow鼓励现场复制相关部分(突出显示,归档) – n611x007 2013-11-06 21:39:00

5

使用handles AKA 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

使用 “标签” 的关键字,比如:

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

然后添加传说像这样:

pyplot.legend() 

传说将保留般粗细,颜色线条属性等

enter image description here