【问题标题】:placing a legend on a subplot in matplotlib, what am I doing wrong?在matplotlib的子图上放置一个图例,我做错了什么?
【发布时间】:2012-10-14 06:06:05
【问题描述】:

我试图在子图中放置一个图例,但我无法做到。这是我正在尝试做的一个示例:

def test():
    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    V = 10
    X = range (V)
    char = 'a'
    leg = []
    legp = []
    for i in range (0,5):
        Y = np.random.randn(V)
        ap = ax1.plot(X,Y)
        legp.append(ap)
        char = chr(ord(char)+1)
        leg.append(char)
    fig.legend(legp,leg)
    fig.show()

这个产量与空图例。我还收到了一堆警告信息:

warnings.warn("Legend 不支持 %s\n使用代理艺术家 \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:用户警告: Legend 不支持 [] 请改用代理艺术家。

http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist

warnings.warn("Legend 不支持 %s\n使用代理艺术家 \n\nhttp://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist\n" % (str(orig_handle),))

我想这与这个“代理艺术家”有关,但它指向的链接指向学习这个开始的链接。

对于那些想知道的人,我只想在图例中包含部分绘制的图。

那我该如何实现呢?

编辑
我在带有 gnome 的 Ubuntu 12.10 上使用 python 2.7.3。

【问题讨论】:

  • 你能在调用legend()之前print(调试)legpleg吗?您的警告告诉您其中一个是空列表(可能两者都是),这意味着您的循环没有正确运行,或者它们 append 语句没有按预期工作。 (另外,请仔细检查此处的代码是否与您的代码完全相同。)
  • @Evert。我用ax1.plot(X,Y)[0] 替换了ax1.plot(X,Y),现在这项工作。您可以阅读 gerogesl 和我的评论线程。谢谢。

标签: python matplotlib legend


【解决方案1】:

奇怪...它似乎对我很好。

编辑:问题来自于解包情节返回对象: ap, = ax1.plot(X,Y)

有关使用逗号的更多信息:

Matplotlib Legends not working

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

Controling line properties

编辑结束

见:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
V = 10
X = range (V)
char = 'a'
leg = []
legp = []
for i in range (0,5):
    Y = np.random.randn(V)
    ap = ax1.plot(X,Y)
    legp.append(ap)
    char = chr(ord(char)+1)
    leg.append(char)
fig.legend(legp,leg)
plt.show()

结果:

【讨论】:

  • 你用的是什么python版本?什么操作系统?
  • 我在 Windows 上使用 python 2.7.3 和 mathplotlib v1.1.0。
  • 你能想出另一种方法来实现这一点吗?
  • 并非没有关于您的错误的更多信息(什么样的子图,...)。但这是一个疯狂的猜测:Matplotlib Legends not working
  • 是的,逗号起到了作用。逗号是什么意思?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-24
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多