图例中的标记类型错误

时间:2014-03-17 15:28:00

标签: python matplotlib

我试图创建一个包含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()

这给了我一个这样的情节:enter image description here

正如您所看到图例中的标记错误,我尝试使用图例处理程序设置图例:

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

这绘制了图表,没有图例,告诉我使用代理艺术家,因为我的标签对象不受支持。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:3)

您的第一次尝试失败,因为您每个循环多次调用绘图命令,因此前四个绘图是蓝色制造商。您的第二次尝试失败,因为plt.plot会返回艺术家列表。您可以通过添加

来使您的借调方法有效
p1, = plt.plot(x,y, 'kD')

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

而不是

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

请注意,

答案 1 :(得分: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循环。


在致电label时,请尝试使用plt.plot关键字为每个地图标记:

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()

enter image description here