我是python的新手,发现了这个出色的PCA双线图建议(绘制PCA加载和在sklearn中的双线图中加载(如R的自动图))。现在,我尝试为图例中的不同目标添加图例。但是该命令plt.legend()不起作用。有一个简单的方法吗?例如,来自上面链接的虹膜数据和双标码。import numpy as npimport matplotlib.pyplot as pltfrom sklearn import datasetsfrom sklearn.decomposition import PCAimport pandas as pdfrom sklearn.preprocessing import StandardScaleriris = datasets.load_iris()X = iris.datay = iris.target#In general a good idea is to scale the datascaler = 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双标有任何建议!还有其他代码,如果添加图例更容易!
添加回答
举报
0/150
提交
取消