如何使用字典键编写图例?

时间:2016-01-17 16:43:12

标签: python python-2.7 matplotlib

我正在尝试可视化以下数据:dictMy = {'apple' : [[0, 1], [0, 2], [3, 2]], 'pear' : [[2, 3], [3, 5], [0, 2]], 'peach' : [[2, 5], [3, 8], [0, 0]]}这是我的代码:

from matplotlib.pyplot import cm
import matplotlib.pyplot as plt
import numpy as np


dictMy = {'apple' : [[0, 1], [0, 2], [3, 2]], 'pear' : [[2, 3], [3, 5], [0, 2]], 'peach' : [[2, 5], [3, 8], [0, 0]]}

color=iter(cm.rainbow(np.linspace(0,1,len(dictMy))))

for key in dictMy:
    curLabel = key
    c=next(color)
    for item in dictMy[key]:
        x = item[0]
        y = item[1]
        plt.scatter(x,y, c = c)
    plt.legend(str(curLabel))
plt.show()

这是我的输出:

results from code

所以,我真的不明白,为什么它以这种方式显示传奇以及如何解决这个问题。我或多或少地理解为什么它是最后一个键,但我不明白为什么它被分成字母。请帮忙。

1 个答案:

答案 0 :(得分:4)

您正在为字典中的每个legend调用key函数。您不需要这样做 - 只需使用字典键标记散点图上的每种类型的点,然后再调用legend函数。以下内容适用:

from matplotlib.pyplot import cm
import matplotlib.pyplot as plt
import numpy as np


dictMy = {'apple' : [[0, 1], [0, 2], [3, 2]], 'pear' : [[2, 3], [3, 5], [0, 2]], 'peach' : [[2, 5], [3, 8], [0, 0]]}
color=iter(cm.rainbow(np.linspace(0,1,len(dictMy))))

for key in dictMy:
    curLabel = key
    c=next(color)
    for idx, item in enumerate(dictMy[key]):
        x = item[0]
        y = item[1]
        if idx == 0:
            plt.scatter(x, y, c=c, label=key)
        else:
            plt.scatter(x, y, c=c)

plt.legend()
plt.show()

<强>输出

enter image description here

相关问题