简体   繁体   English

使用Python使用散点图绘制包括原始数据在内的PCA结果

[英]Plotting PCA results including original data with scatter plot using Python

I have conducted PCA on iris data as an exercise. 我作为练习对虹膜数据进行了PCA。 Here is my code: 这是我的代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use("ggplot")
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA # as sklearnPCA
import pandas as pd
#=================
df = pd.read_csv('iris.csv');
# Split the 1st 4 columns comprising values
# and the last column that has species
X = df.ix[:,0:4].values
y = df.ix[:,4].values

X_std = StandardScaler().fit_transform(X);  # standardization of data

# Fit the model with X_std and apply the dimensionality reduction on X_std.
pca = PCA(n_components=2) # 2 PCA components;
Y_pca = pca.fit_transform(X_std)

# How to plot my results???? I am struck here! 

Please advise on how to plot my original iris data and the PCAs derived using a scatter plot. 请提供有关如何绘制原始虹膜数据和使用散点图得出的PCA的建议。

Here is the way I think you can visualize it. 我认为这是可视化的方式。 I'll put PC1 on X-Axis and PC2 in Y-Axis and color each point based on its category. 我将PC1放在X轴上,将PC2放在Y轴上,并根据其类别为每个点着色。 Here is the code: 这是代码:

#first we need to map colors on labels
dfcolor = pd.DataFrame([['setosa','red'],['versicolor','blue'],['virginica','yellow']],columns=['Species','Color'])
mergeddf = pd.merge(df,dfcolor)

#Then we do the graph
plt.scatter(Y_pca[:,0],Y_pca[:,1],color=mergeddf['Color'])
plt.show()

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

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