gpt4 book ai didi

python - PCA无法在散点图上获取颜色

转载 作者:行者123 更新时间:2023-12-01 08:41:53 29 4
gpt4 key购买 nike

我正在自己做一个小型项目。我正在用 PCA 尝试这个东西。绘制图表后,我似乎无法获取颜色。这些是我的代码的以下步骤。在此之前,我已经缩放并转换了数据。缩放后我做了 PCA。这些是步骤。第一:

from sklearn.decomposition import PCA
pca= PCA(n_components= 2)
pca.fit(scaled_data)

x_pca= pca.transform(scaled_data)

principaldf= pd.DataFrame(data=x_pca,
columns=['principal component 1',
'principal component 2'])

在此之后,我组合了两个数据帧并得到了这个。

new_df= principaldf.join(df_features)
new_df.head()

enter image description here

接下来我尝试使用下面的代码绘制图表:

color= ['r','g']
plt.scatter(x_pca[:, 0], x_pca[:, 1],
edgecolor='none', alpha=0.5, c= color)
plt.xlabel('component 1')
plt.ylabel('component 2')

我收到这个错误

ValueError: 'c' argument has 2 elements, which is not acceptable for use with 'x' with size 261, 'y' with size 261.

enter image description here

任何人都可以提供建议或帮助吗?希望我的问题足够清楚。谢谢!

最佳答案

您可以尝试以下操作:

性别分配数值:

new_df['Gender'] = new_df['Gender'].replace({'Male':0, 'Female':1})

然后使用颜色和 cmap 进行绘图:

plt.scatter(x_pca[:, 0], x_pca[:, 1], edgecolor='none', alpha=0.5,
c=new_df['Gender'], cmap='RdYlGn')

当您传入像 ['r', 'g'] 这样的 2 项列表时,它不知道哪些点应该是哪种颜色

关于python - PCA无法在散点图上获取颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53466673/

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