PCA 无法在散点图上获取颜色
PCA can't get color on scatterplot
我正在自己做一个小项目。我正在用 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()
接下来我尝试使用以下代码绘制图形:
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.
任何人都可以提供建议或帮助吗?希望我的问题足够清楚。谢谢!
您可以尝试类似的方法:
给Gender
赋数值:
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 项列表时,它不知道哪些点应该是哪种颜色
我正在自己做一个小项目。我正在用 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()
接下来我尝试使用以下代码绘制图形:
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.
任何人都可以提供建议或帮助吗?希望我的问题足够清楚。谢谢!
您可以尝试类似的方法:
给Gender
赋数值:
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 项列表时,它不知道哪些点应该是哪种颜色