【问题标题】:Matplotlib Legends not workingMatplotlib 图例不起作用
【发布时间】:2012-08-12 13:23:50
【问题描述】:

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

我发现错误指向我的链接在诊断错误源时非常无用。

【问题讨论】:

    标签: python plot matplotlib


    【解决方案1】:

    你应该添加逗号:

    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#adjusting-the-order-of-legend-items

    line, = plot(x,sin(x)) what does comma stand for?

    【讨论】:

      【解决方案2】:

      使用handles 又名Proxy 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()
      

      【讨论】:

        【解决方案3】:

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

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

        然后像这样添加图例:

        plt.legend()
        

        图例将保留线条属性,如粗细、颜色等。

        【讨论】:

          【解决方案4】:

          在绘制图形时使用标签,然后只有你可以使用图例。 x 轴名称和 y 轴名称与图例名称不同。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-04-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-05-26
            • 1970-01-01
            • 2023-03-18
            相关资源
            最近更新 更多