Matplotlib Legends不工作

Mik*_*lla 78 python plot matplotlib

自从升级matplotlib以来,每次尝试创建图例时都会出现以下错误:

/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),))
Run Code Online (Sandbox Code Playgroud)

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

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()
Run Code Online (Sandbox Code Playgroud)

我发现错误指向我的链接在诊断错误源方面毫无用处.

app*_*tor 146

你应该添加逗号:

plot1, = plt.plot(a,b)
plot2, = plt.plot(a,c)
Run Code Online (Sandbox Code Playgroud)

你需要逗号的原因是因为plt.plot()返回一个行对象的元组,无论从命令实际创建了多少个.如果没有逗号,"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))逗号代表什么?

  • 你能在这里复制/添加解释吗?stackoverflow鼓励现场复制相关部件(突出显示,存档) (2认同)

Yts*_*oer 9

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

pyplot.plot(x, y, label='x vs. y')
Run Code Online (Sandbox Code Playgroud)

然后像这样添加图例:

pyplot.legend()
Run Code Online (Sandbox Code Playgroud)

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

在此处输入图片说明


ppa*_*ojr 7

使用handlesAKAProxy artists

import matplotlib.lines as mlines
import matplotlib.pyplot as plt
# defining legend style and data
blue_line = mlines.Line2D([], [], color='blue', label='My Label')
reds_line = mlines.Line2D([], [], color='red', label='My Othes')

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

plt.show()
Run Code Online (Sandbox Code Playgroud)