Hi, here is a callback that I use for PCA:
### Chart 5 ###
@app.callback(
Output("card_graph_5", "figure"),
Input('datatable-interactivity', "derived_virtual_data"),
Input('datatable-interactivity', "derived_virtual_selected_rows"),
Input("card_choice_7", "value"),
Input("card_choice_8", "value")
)
def pca(rows, derived_virtual_selected_rows, card_choice_7, card_choice_8):
if derived_virtual_selected_rows is None:
derived_virtual_selected_rows = []
dff = df if rows is None else pd.DataFrame(rows)
df_X = dff[card_choice_7]
# Scale
scaler = StandardScaler()
scaler.fit(df_X)
scaled_data = scaler.transform(df_X)
# Fit
pca = PCA(n_components=2)
components = pca.fit_transform(scaled_data)
# Loadings
loadings = pca.components_.T * np.sqrt(pca.explained_variance_)
# Graph
fig = px.scatter(
components,
x=0,
y=1,
color=dff[card_choice_8],
labels = { '0': f'PC 0 ({pca.explained_variance_ratio_[0].round(4)*100}%)',
'1': f'PC 1 ({pca.explained_variance_ratio_[1].round(4)*100}%)'},
title='PCA'
# hover_data=dff['Price']
)
for i, feature in enumerate(card_choice_7):
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,
)
return fig
Unfortunately, whenever I add the parameter hover_data or custom_data, it is not drawn at all.
Docs says that it accepts the Series and dff[‘Price’] does return the Series.
Can you help me out?
Thank you.