如何向scatterp添加图例

2024-05-21 02:37:27 发布

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

我正在为机器学习课程做练习。 我在一个矩阵上附加了一个数组形式的图像数据集到datamatrix中,然后我将其标准化,然后计算主成分。 Labels是一个数组,包含每个图像的标签(即包含标签的子目录) 我需要想象一对主成分,在这一部分中是前两个。教授的建议是使用散点图函数,我找到了seaborn.散点图功能似乎更好,但没有两个我设法把一个与标签上的名字图例。你知道吗

pca = PCA()
X_t = pca.fit_transform(datamatrix)
X_r = pca.inverse_transform(X_t)

plt.figure(figsize=(25,5))

colours = ['r','g','b','p']
plt.subplot(1, 3, 1)
sns.scatterplot(X_t[:,0], X_t[:,1], hue=labels, palette=colours, legend='full')
plt.title('PC 1 and 2')

我不熟悉Python和机器学习库

编辑: 正如我建议的那样,我试着修改cod:

data = {"x" : X_t[:,0], "y" : X_t[:,1], "label" : labels}
sns.scatterplot(x="x", y="y", hue="label", palette=colours, data=data, legend='full')

但我得到了相同的结果:我有图例,但没有标签的名称 capture


Tags: 图像机器datatransformplt标签数组建议
2条回答

在显示绘图之前,使用以下方法添加图例:

plt.legend()

Seaborn scatterplot将自动创建一个图例,如the documentation的第二个示例所示。但是,它确实需要将数据放在类似于字典的结构中,这在数据帧中很常见。你知道吗

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

data = {"x" : np.random.rand(10),
        "y" : np.random.rand(10),
        "label" : np.random.choice(["Label 1", "Label 2"], size=10)}

sns.scatterplot(x="x", y="y", hue="label", data=data)
plt.show()

enter image description here

要通过matplotlib的scatter实现同样的功能,您需要自己创建图例,这确实有点麻烦,但可能有助于理解。你知道吗

import numpy as np
import matplotlib.pyplot as plt

data = {"x" : np.random.rand(10),
        "y" : np.random.rand(10),
        "label" : np.random.choice(["Label 1", "Label 2"], size=10)}

labels, inv = np.unique(data["label"], return_inverse=True)
scatter = plt.scatter(x="x", y="y", c = inv, data=data)

handles = [plt.Line2D([],[],marker="o", ls="", 
                      color=scatter.cmap(scatter.norm(yi))) for yi in np.unique(inv)]
plt.legend(handles, labels)

plt.show()

enter image description here

另见Add legend to scatter plot (PCA)

相关问题 更多 >