简体   繁体   English

plt.legend 仅将第一个元素添加到散点图

[英]plt.legend only adds first element to scatter plot

I am trying to add a legend to my scatter plot with 13 classes, however, with my code below, I am only able to get the first label.我正在尝试在我的散点图中添加一个包含 13 个类的图例,但是,使用下面的代码,我只能获得第一个标签。 Can you assist me in generating the full list to show up in the legend of the scatter plot?您能帮助我生成完整列表以显示在散点图的图例中吗?

Here is my example code:这是我的示例代码:

from sklearn.datasets import make_blobs
from matplotlib import pyplot
from pandas import DataFrame
# generate 2d classification dataset
X, y = make_blobs(n_samples=1000, centers=13, n_features=2)

classes = [f"class {i}" for i in range(13)]

#fig = plt.figure()
plt.figure(figsize=(15, 12))
scatter = plt.scatter(
    x=X[:,0],
    y=X[:,1],
    s = 20, 
    c = y, 
    cmap='Spectral'
    #c=[sns.color_palette()[x] for x in y_train_new]
    )
plt.gca().set_aspect('equal', 'datalim')
plt.legend(classes)
plt.title('Dataset', fontsize=24)

You can do that by replacing the plt.legend(classes) in your code by this line... I hope this is what you are looking for.你可以通过用这一行替换代码中的plt.legend(classes)来做到这一点......我希望这是你正在寻找的。 I am using matplotlib 3.3.4.我正在使用 matplotlib 3.3.4。

plt.legend(handles=scatter.legend_elements()[0], labels=classes)

Output plot输出图

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM