我正在尝试使用 Plotly 制作交互式 PCA 图。我在突出显示用户希望在图中看到的某个标记时遇到一些麻烦。
标记周围没有突出显示,而是有一个正方形。
我对代码的尝试:
from sklearn.datasets import make_blobs
import pandas as pd
import plotly.express as px
X, y = make_blobs(n_samples=30, centers=3, n_features=2,
random_state=0)
ff = PCA(n_components= 2)
clusters = pd.DataFrame(data = ff.fit_transform(X), columns = ['PC1', 'PC2'])
clusters['target'] = y
id = [0, 4, 7]
updatemenus = [dict(buttons=list(dict(label = idd ,method = 'relayout', args = ['shapes', [dict(markers = dict(color = 'Red', size = 120), type = "markers", xref = 'x', yref = 'y', x0 = clusters.loc[idd, 'PC1'], y0=clusters.loc[idd, 'PC2'])]]) for idd in id))]
fig = px.scatter(clusters, x = 'PC1', y = 'PC2', color = 'target', hover_data = ['target'])
fig.update_layout(updatemenus = updatemenus)
fig.show()
我做错了什么:)
type
应该是'circle' | 'rect' | 'path' | 'line'
之一,我猜你可能想使用'circle'
而不是'markers'
。
size = 1/100 # ~1% of the x|y range
rx = (clusters['PC1'].max() - clusters['PC1'].min()) * size
ry = (clusters['PC2'].max() - clusters['PC2'].min()) * size
updatemenus = [dict(
buttons=[dict(
label='None',
method='relayout',
args=['shapes', []]
)] + [dict(
label=idd,
method='relayout',
args=[{
'xaxis.autorange': True,
'yaxis.autorange': True,
'shapes': [{
'type': 'circle',
'layer': 'below',
'xref': 'x',
'yref': 'y',
'x0': clusters.loc[idd, 'PC1'] - rx,
'y0': clusters.loc[idd, 'PC2'] - ry,
'x1': clusters.loc[idd, 'PC1'] + rx,
'y1': 0 if idd is None else clusters.loc[idd, 'PC2'] + ry,
'opacity': 0.3,
'fillcolor': 'red'
}]
}]
) for idd in id]
)]