matplotlib 如何在for循环中添加图例[重复]

frebpwbc  于 2023-06-23  发布在  其他
关注(0)|答案(2)|浏览(121)
    • 此问题已在此处有答案**:

Multiple legends in for-loop(2个答案)
9天前关闭
我正在尝试在matplotlib中分散一些数据点,但在正确显示图例时遇到了一些问题。导入和初始化后

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

rng = np.random.default_rng(0)

x = rng.uniform(0, 3, 5)
y = rng.uniform(0, 5, 5)
labels = ["a", "b", "c", "d", "e"]
colors = [plt.cm.plasma(i / float(len(labels))) for i in range(len(labels))]

我运行一个(比我想象的要少)简单的plt.scatter

# scatter strategy 1
scatter1 = plt.figure()
scatter1 = plt.scatter(
    x=x,
    y=y,
    c=colors,
    cmap=cm.plasma,
    label=labels,
)
handles, labels = scatter1.legend_elements(num=list(np.unique(labels)))
plt.legend(handles, labels, loc="lower right")
plt.show()

只是为了发现句柄和标签都是空列表。这将导致图例不显示。我该如何解决这个问题,为什么?
在sidenote上,我还尝试用for循环逐个绘制每个数据点,如下所示:

# scatter strategy 2
scatter2 = plt.figure()
unique = np.unique(labels)

for i, u, color in zip(range(len(unique)), unique, colors):
    xi = x[i]
    yi = y[i]
    plt.scatter(xi, yi, color=color, cmap=cm.plasma, label=str(unique))
plt.show()

没有好的,因为它似乎是没有被“填充”的数据。为什么会这样,我该如何修复它?如何正确编译后一个示例中的图例?

idv4meu8

idv4meu81#

当你用for循环寻找答案时,第二个(策略2)就是我修改的那个。看看这是不是你要找的...

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

rng = np.random.default_rng(0)

x = rng.uniform(0, 3, 5)
y = rng.uniform(0, 5, 5)
labels = ["a", "b", "c", "d", "e"]
colors = [plt.cm.plasma(i / float(len(labels))) for i in range(len(labels))]

# scatter strategy 2
scatter2 = plt.figure()
unique = np.unique(labels)

for i in range(len(unique)): ##Simplified a bit
    plt.scatter(x[i], y[i], color=colors[i], cmap=cm.plasma, label=labels[i])  ## Updates here... should be colors[i] and labels[i]

plt.legend()  ## You will need this
plt.show()

piztneat

piztneat2#

你不需要自己计算颜色,让matplotlib来计算,只需要按原样使用你的标签:

import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(0)

x = rng.uniform(0, 3, 5)
y = rng.uniform(0, 5, 5)
labels = ["a", "b", "c", "d", "e"]

scatter1 = plt.scatter(
    x=x,
    y=y,
    c=range(len(labels)),
    cmap="plasma",
    vmax=len(labels)
)
handles, _ = scatter1.legend_elements()
plt.legend(handles, labels, loc="lower right")

相关问题