在该列中用 类 标记绘图图例
Label the plot legend with the classes in that column
我无法标记图,它在 c=df["hypothyroid"] 列中显示 1,2,3 属性。
我尝试了 legend(labels=[1,2,3]) 甚至 gca().legend(labels=1,2,3]).
print("Before PCA: ", df.shape)
seed = 7
pca = PCA(n_components=2, random_state=seed)
df_pca = pca.fit_transform(df)
pca_2 = plt.scatter(df_pca[:,0], df_pca[:,1], c=df["hypothyroid"],
cmap="autumn")
plt.title("2_components PCA")
plt.xlabel("Principal Component 1")
plt.ylabel("Pringipal Component 2")
plt.gca().legend(["0","1","2"])
plt.show()
print("After PCA: ", df_pca.shape)
我需要情节有 1 2 3 甲状腺功能减退症的传说 类。像这个图像显示了虹膜分类。
解决方案
根据 this example from the Matplotlib docs,在散点图中为每个类别获取标签的可接受方法是 运行 plt.scatter
一次用于每个类别中的数据。这是一个完整的示例(仍然使用 Iris 数据集):
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
iris = datasets.load_iris()
X = iris.data
y = iris.target
target_names = iris.target_names
pca = PCA(n_components=2)
df_pca = pca.fit_transform(X)
for label in np.unique(y):
plt.scatter(df_pca[y==label, 0], df_pca[y==label, 1], label=label)
plt.legend()
plt.show()
输出:
警告
就像我的示例中的 y
数组一样,您必须已经有一些数据结构将类别标签与每个数据点相匹配。否则,Matplotlib(或任何绘图程序)将无法确定哪些点属于哪个类别。
我无法标记图,它在 c=df["hypothyroid"] 列中显示 1,2,3 属性。
我尝试了 legend(labels=[1,2,3]) 甚至 gca().legend(labels=1,2,3]).
print("Before PCA: ", df.shape)
seed = 7
pca = PCA(n_components=2, random_state=seed)
df_pca = pca.fit_transform(df)
pca_2 = plt.scatter(df_pca[:,0], df_pca[:,1], c=df["hypothyroid"],
cmap="autumn")
plt.title("2_components PCA")
plt.xlabel("Principal Component 1")
plt.ylabel("Pringipal Component 2")
plt.gca().legend(["0","1","2"])
plt.show()
print("After PCA: ", df_pca.shape)
我需要情节有 1 2 3 甲状腺功能减退症的传说 类。像这个图像显示了虹膜分类。
解决方案
根据 this example from the Matplotlib docs,在散点图中为每个类别获取标签的可接受方法是 运行 plt.scatter
一次用于每个类别中的数据。这是一个完整的示例(仍然使用 Iris 数据集):
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
iris = datasets.load_iris()
X = iris.data
y = iris.target
target_names = iris.target_names
pca = PCA(n_components=2)
df_pca = pca.fit_transform(X)
for label in np.unique(y):
plt.scatter(df_pca[y==label, 0], df_pca[y==label, 1], label=label)
plt.legend()
plt.show()
输出:
警告
就像我的示例中的 y
数组一样,您必须已经有一些数据结构将类别标签与每个数据点相匹配。否则,Matplotlib(或任何绘图程序)将无法确定哪些点属于哪个类别。