Matplotlib Legends 不起作用 [英] Matplotlib Legends not working
问题描述
自从升级 matplotlib 后,我在尝试创建图例时都会收到以下错误:
Ever since upgrading matplotlib I get the following error whenever trying to create a legend:
/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
Use proxy artist instead.
http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist
" % (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
Use proxy artist instead.
http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist
" % (str(orig_handle),))
这甚至发生在像这样的简单脚本中:
This even occurs with a trivial script like this:
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()
我发现错误指向我在诊断错误来源时非常无用的链接.
I've found the link that the error points me towards pretty useless in diagnosing the source of the error.
推荐答案
你应该添加逗号:
plot1, = plt.plot(a,b)
plot2, = plt.plot(a,c)
你需要逗号的原因是因为 plt.plot() 返回一个线对象元组,不管实际上有多少是从命令中创建的.如果没有逗号,plot1"和plot2"是元组而不是线对象,这使得后面对 plt.legend() 的调用失败.
The reason you need the commas is because plt.plot() returns a tuple of line objects, no matter how many are actually created from the command. Without the comma, "plot1" and "plot2" are tuples instead of line objects, making the later call to plt.legend() fail.
逗号隐式地解包结果,因此plot1"和plot2"不是元组,而是自动成为元组中的第一个对象,即您实际想要的线对象.
The comma implicitly unpacks the results so that instead of a tuple, "plot1" and "plot2" automatically become the first objects within the tuple, i.e. the line objects you actually want.
http://matplotlib.sourceforge.net/users/legend_guide.html#adjusting-the-order-of-legend-items
line, = plot(x,sin(x)) 逗号代表什么?
这篇关于Matplotlib Legends 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!