Matplotlib传奇不工作

自升级matplotlib以来,每当尝试创build图例时都会收到以下错误消息:

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

这甚至发生这样一个简单的脚本:

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

我发现这个错误指向的链接在诊断错误的根源方面是无用的。

你应该添加逗号:

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

你需要逗号的原因是因为plt.plot()返回一个行对象的元组,不pipe从命令实际创build了多less个元组。 如果没有逗号,“plot1”和“plot2”是元组而不是线对象,使得稍后调用plt.legend()失败。

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

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

line,= plot(x,sin(x))逗号代表什么?

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

使用“标签”关键字,如下所示:

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

然后添加像这样的传说:

 pyplot.legend() 

图例将保留线条属性,如厚度,颜色等

在这里输入图像说明