图例中的标记类型错误

-1 投票
2 回答
1093 浏览
提问于 2025-04-17 22:40

我正在尝试创建一个简单的图表,里面包含4组数据,这4个列表的绘制方式如下:

for x,y in d1:
    p1 = plt.plot(x,y, 'bo')
for x,y in d14:
    p2 = plt.plot(x,y, 'rs')
for x,y in d56:
    p3 = plt.plot(x,y, 'gx')
for x,y in d146:
    p4 = plt.plot(x,y, 'kD')
plt.legend(['1', '14', '56', '146'], loc='upper left',numpoints = 1)
plt.show()

这样我得到了一个像这样的图表:在这里输入图片描述

你可以看到,图例中的标记是错误的,我尝试用图例处理器来设置图例:

plt.legend([p1, p2, p3, p4], ["1", "14", "56", "146"], loc="upper left")

这会绘制出图表,但没有图例,并告诉我应该使用代理艺术家,因为我的标签对象不被支持。任何帮助都会很感激。

2 个回答

1

编辑:

我发现你绘制每个点的方式有点问题。可以试试使用 zip:

In [1]: arr = [(0, 0), (1, 2), (2, 4), (3, 6), (4, 8)]
In [2]: zip(*arr)
Out[2]: [(0, 1, 2, 3, 4), (0, 2, 4, 6, 8)]

这样,你就可以用

x, y = zip(*d1)
plt.plot(x, y, 'bo', label='d1')
x, y = zip(*d14)
plt.plot(x, y, 'rs', label='d14')
x, y = zip(*d56)
plt.plot(x, y, 'gx', label='d56')
x, y = zip(*d146)
plt.plot(x, y, 'kD', label='d146')
plt.legend()

来代替使用 for 循环了。


在调用 plt.plot 时,试着用 label 关键字给每个图标加个标签:

In [1]: import numpy as np
In [2]: import matplotlib.pyplot as plt
In [3]: x1 = np.arange(5)
In [4]: y1, y2, y3, y4 = np.arange(5), np.arange(0, 10, 2), np.arange(0, 2.5, 0.5), np.random.rand(5)
In [5]: plt.plot(x1, y1, 'bo', label='1')
In [6]: plt.plot(x1, y2, 'rs', label='2')
In [7]: plt.plot(x1, y3, 'gx', label='3')
In [8]: plt.plot(x1, y4, 'kD', label='4')
In [9]: plt.legend()
Out[9]: <matplotlib.legend.Legend at 0x2b5aed0>
In [10]: plt.show()

在这里输入图片描述

3

你第一次尝试失败是因为你在每次循环中调用绘图命令太多次,所以前四个图都是蓝色的标记。你第二次尝试失败是因为 plt.plot 返回的是一个艺术家列表。你可以通过添加

p1, = plt.plot(x,y, 'kD')

或者

p1 = plt.plot(x,y, 'kD')[0]

来让你的第二种方法成功,而不是

p1 = plt.plot(x,y, 'kD')

注意 , 的使用。

撰写回答