简体   繁体   中英

Python matplotlib.pyplot Bigram Plot as Plotly Plot

I'm trying to combine my PCA and my loading plot into one bigram. I found this solution for a matplotlib.pyplot, however, I would like to produce the same plot in plotly. Can someone help me out on how I could produce these with 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()

Code and Plot with Pyplot:

使用 Pyplot 编码和绘图

Edit: Since my question is supposed to be more focused (: :

I can rereate the PCA part in plotly: PlotlyPlot

However i have no idea how or even if i could recreate the "Loading Plot" in this plot.

Could i maybe stack an Quiver Plot on the previous plot in order to achieve my goal?

Could it work similar to this: Arrow Overlay ?

Well. After browsing some more over the Plotly Documentation i was able to find what i was looking for: https://plotly.com/python/pca-visualization/ on this link under the "Visualize Loadings" section they describe a nice way to do this :)

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

Picture from docu

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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