Matplotlib 图例不工作

2024-06-21

自从升级 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),))

这甚至发生在像这样的简单脚本中:

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() 返回线条对象的元组,无论实际从命令创建了多少个。如果没有逗号,“plot1”和“plot2”是元组而不是线对象,导致稍后对 plt.legend() 的调用失败。

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

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

line, =plot(x,sin(x)) 逗号代表什么? https://stackoverflow.com/questions/10422504/line-plotx-sinx-what-does-comma-stand-for?rq=1

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Matplotlib 图例不工作 的相关文章

随机推荐