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

2024-10-01 17:38:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试可视化以下数据: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

所以,我真的不明白,为什么它会以这样的方式展示传奇故事,以及如何解决这个问题。我或多或少明白为什么它是所有钥匙中的最后一个,但我不明白它为什么被分成字母。求你了,救命。在


Tags: keyimportappleformatplotlibasnpcm
1条回答
网友
1楼 · 发布于 2024-10-01 17:38:23

此时,您正在为字典中的每个key调用legend函数。您不需要这样做-只需用dictionary键标记散点图上的每种类型的点,然后调用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, c in zip(dictMy, 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

相关问题 更多 >

    热门问题