在使用Plotly通过在散点图中将光标悬停在点上检索悬停数据时,我遇到了一个问题。从Dash应用程序中检索到的悬停数据似乎包含相同的pointNumber和pointIndex,用于同一地块中的多个点。这样,当在相应的点上盘旋时,就不可能显示与给定实例关联的正确信息。
下面是一个简化的例子,可以在木星笔记本上运行。最后,我将希望在悬停上显示图像。
from sklearn.datasets import load_iris
import numpy as np
import pandas as pd
from jupyter_dash import JupyterDash
from dash import dcc, html, Input, Output, no_update
import plotly.express as px
# Loading iris data to pandas dataframe
data = load_iris()
images = data.data
labels = data.target
df = pd.DataFrame(images[:, :2], columns=["feat1", "feat2"])
df["label"] = labels
# Color for each class
color_map = {0: "setosa",
1: "versicolor",
2: "virginica"}
colors = [color_map[l] for l in labels]
df["color"] = colors
pd.set_option("display.max_rows", None, "display.max_columns", None)
print(df)
# Setup plotly scatter plot
fig = px.scatter(df, x="feat1", y="feat2", color="color")
fig.update_traces(hoverinfo="none",
hovertemplate=None)
# Setup Dash
app = JupyterDash(__name__)
app.layout = html.Div(className="container",
children=[dcc.Graph(id="graph-5", figure=fig, clear_on_unhover=True),
dcc.Tooltip(id="graph-tooltip-5", direction="bottom")])
@app.callback(Output("graph-tooltip-5", "show"),
Output("graph-tooltip-5", "bbox"),
Output("graph-tooltip-5", "children"),
Input("graph-5", "hoverData"))
def display_hover(hoverData):
if hoverData is None:
return False, no_update, no_update
print(hoverData)
hover_data = hoverData["points"][0]
bbox = hover_data["bbox"]
num = hover_data["pointNumber"]
children = [html.Div([html.Img(style={"height": "50px",
"width": "50px",
"display": "block",
"margin": "0 auto"}),
html.P("Feat1: {}".format(str(df.loc[num]["feat1"]))),
html.P("Feat2: {}".format(str(df.loc[num]["feat2"])))])]
return True, bbox, children
if __name__ == "__main__":
app.run_server(mode="inline", debug=True)例如,通过print(Df)检索的两个实例可以观察到这个问题:
索引feat1 feat2标签颜色
31 5.4 3.4 0 setosa
131 7.9 3.8 2
通过print( pointNumber )检索到的两个pointIndex都被分配给了相同的HoverData:
{“点数”:{“曲线编号”:2,“点编号”:31,“点索引”:31,“x”:7.9,'y':3.8,'bbox':{'x0':1235.5,'x1':1241.5,'y0':152.13,'y1':158.13}}{“点”:{“曲线编号”:0,“点数”:31,“点索引”:31,“x”:5.4,'y':3.4,'bbox':{'x0':481.33,'x1':487.33,'y0':197.38,'y1':203.38}
这是在这两个实例上盘旋时的可视化。对于右侧的图像,悬停信息是错误的。

有趣的是,当使用
fig = px.scatter(df, x="feat1", y="feat2", color="label")但是,这将导致图例以连续的方式显示,并禁用有选择地可视化与HTML中特定类相关的实例的可能性。
这是个窃听器还是我忽略了什么?任何帮助都是非常感谢的!
发布于 2021-11-25 11:29:54
结果,我错误地认为pointNumber和pointIndex是独一无二的。只要在color中使用非数字列作为px.scatter()参数,就会重新编号每个类的点数和索引。通过将curveNumber与pointNumber和pointIndex结合起来,可以唯一地识别散射点中的点。
一个潜在的解决方案是为每个类生成单独的索引,并将它们添加到dataframe中:
curve_indices = np.array([np.arange(0, num_samples) for num_samples in np.unique(class_annot, return_counts=True)[1]], dtype="object")
curve_indices = np.concatenate(curve_indices).ravel()
df["curve_index"] = curve_indices在回调函数中,可以使用
df_index = df[(df.label == curve) & (df.curve_index == num)].index[0]https://stackoverflow.com/questions/70050831
复制相似问题