gpt4 book ai didi

python - 描述没有重复的图例

转载 作者:太空宇宙 更新时间:2023-11-03 11:08:17 25 4
gpt4 key购买 nike

我想为 Matplotlib 散点图添加彩色图例。这是我的代码:

xs = [1, 2, 1, 4, 3, 2]
ys = [1, 3, 2, 2, 3, 1]
labels = [1, 1, 0, 2, 1, 3]

label_dict = {0: 'r', 1: 'k', 2: 'b', 3: 'g'}
legend_dict = {0: 'foo', 1: 'bar', 2: 'baz', 3: 'biff'}

for x, y, label in zip(xs, ys, labels):
plt.scatter(x, y, c=label_dict.get(label), label=legend_dict.get(label))

plt.legend()
plt.show()

enter image description here

如何让图例只为每种颜色显示一个标签,而不是为每个点显示一个标签?

最佳答案

您可以跟踪您看到的标签:

import pylab as plt

xs = [1, 2, 1, 4, 3, 2]
ys = [1, 3, 2, 2, 3, 1]
labels = [1, 1, 0, 2, 1, 3]

label_dict = {0: 'r', 1: 'k', 2: 'b', 3: 'g'}
legend_dict = {0: 'foo', 1: 'bar', 2: 'baz', 3: 'biff'}

seen = set()
for x, y, label in zip(xs, ys, labels):
if label not in seen:
plt.scatter(x, y, c=label_dict.get(label), label=legend_dict.get(label))
else:
plt.scatter(x, y, c=label_dict.get(label))
seen.add(label)

plt.legend()
plt.show()

如果您愿意,可以将 if/else 子句压缩为 1 行:

seen = set()
for x, y, label in zip(xs, ys, labels):
plt.scatter(x, y, c=label_dict.get(label), label=legend_dict.get(label) if label not in seen else None)
seen.add(label)

我认为我个人更愿意将数据分组。换句话说,我可能会将具有相同标签的所有数据存储在一起,然后您只需要为每种标签类型发出一个 plot 命令:

import numpy as np
import pylab as plt

xs = [1, 2, 1, 4, 3, 2]
ys = [1, 3, 2, 2, 3, 1]
labels = [1, 1, 0, 2, 1, 3]

xs = np.array(xs)
ys = np.array(ys)
labels = np.array(labels)

labels_masks =( (x,(labels == x)) for x in set(labels))
data_dict = dict( (lbl,(xs[mask],ys[mask])) for lbl,mask in labels_masks )


label_dict = {0: 'r', 1: 'k', 2: 'b', 3: 'g'}
legend_dict = {0: 'foo', 1: 'bar', 2: 'baz', 3: 'biff'}

for label,data in data_dict.items():
x,y = data
plt.scatter(x,y,c=label_dict.get(label),label=legend_dict.get(label))

plt.legend()
plt.show()

关于python - 描述没有重复的图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13607545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com