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

时间:2015-11-05 00:31:28

标签: python numpy matplotlib scikit-learn pca

我作为练习在虹膜数据上进行了PCA。这是我的代码:

#!/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! 

请告知如何使用散点图绘制原始虹膜数据和PCA。

1 个答案:

答案 0 :(得分:3)

这是我认为你可以想象它的方式。我将PC1放在X轴上,将PC2放在Y轴上,并根据其类别为每个点着色。这是代码:

#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()