猿问

将图例添加到散点图(PCA)

我是python的新手,发现了这个出色的PCA双线图建议(绘制PCA加载和在sklearn中的双线图中加载(如R的自动图))。现在,我尝试为图例中的不同目标添加图例。但是该命令plt.legend()不起作用。


有一个简单的方法吗?例如,来自上面链接的虹膜数据和双标码。


import numpy as np

import matplotlib.pyplot as plt

from sklearn import datasets

from sklearn.decomposition import PCA

import pandas as pd

from sklearn.preprocessing import StandardScaler


iris = datasets.load_iris()

X = iris.data

y = iris.target

#In general a good idea is to scale the data

scaler = StandardScaler()

scaler.fit(X)

X=scaler.transform(X)    


pca = PCA()

x_new = pca.fit_transform(X)


def myplot(score,coeff,labels=None):

    xs = score[:,0]

    ys = score[:,1]

    n = coeff.shape[0]

    scalex = 1.0/(xs.max() - xs.min())

    scaley = 1.0/(ys.max() - ys.min())

    plt.scatter(xs * scalex,ys * scaley, c = y)

    for i in range(n):

        plt.arrow(0, 0, coeff[i,0], coeff[i,1],color = 'r',alpha = 0.5)

        if labels is None:

            plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, "Var"+str(i+1), color = 'g', ha = 'center', va = 'center')

        else:

            plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, labels[i], color = 'g', ha = 'center', va = 'center')

plt.xlim(-1,1)

plt.ylim(-1,1)

plt.xlabel("PC{}".format(1))

plt.ylabel("PC{}".format(2))

plt.grid()


#Call the function. Use only the 2 PCs.

myplot(x_new[:,0:2],np.transpose(pca.components_[0:2, :]))

plt.show()

欢迎对PCA双标有任何建议!还有其他代码,如果添加图例更容易!


倚天杖
浏览 444回答 1
1回答
随时随地看视频慕课网APP

相关分类

Python
我要回答