我正在尝试将我的PCA和装载区合并为一个二元组。我找到了this的matplotlib.pyplot解决方案,但是,我想在plotly中生成相同的图。有人可以帮我解决如何用情节地制作这些东西吗?
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, featurenames[i], 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()
myplot(components,np.transpose(pca.components_))
plt.show()
带有Pyplot的代码和绘图:
编辑:由于我的问题应该更加集中(::
我可以重新创建PCA部分: PlotlyPlot
但是我不知道如何甚至可以在此图中重新创建“加载图”。
为了实现我的目标,我可以在上一个剧情上叠加一个Quiver Plot吗?
它的工作原理是否类似于:Arrow Overlay?
答案 0 :(得分:0)
好吧。在Plotly文档中浏览了更多内容之后,我能够找到所需的内容: https://plotly.com/python/pca-visualization/在“可视化负载”部分下的此链接上,描述了一种执行此操作的好方法:)
import plotly.express as px
from sklearn.decomposition import PCA
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
df = px.data.iris()
features = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
X = df[features]
pca = PCA(n_components=2)
components = pca.fit_transform(X)
loadings = pca.components_.T * np.sqrt(pca.explained_variance_)
fig = px.scatter(components, x=0, y=1, color=df['species'])
for i, feature in enumerate(features):
fig.add_shape(
type='line',
x0=0, y0=0,
x1=loadings[i, 0],
y1=loadings[i, 1]
)
fig.add_annotation(
x=loadings[i, 0],
y=loadings[i, 1],
ax=0, ay=0,
xanchor="center",
yanchor="bottom",
text=feature,
)
fig.show()