Matplotlib图例不起作用 [英] 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\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),))
这甚至在像这样的琐碎脚本中也会发生:
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-legend项目
这篇关于Matplotlib图例不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!