- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在使用 Plotly 和 Dash 通过将光标悬停在散点图中的点上来检索悬停数据时,我遇到了一个问题。从 Dash 应用程序检索的悬停数据似乎包含同一图中多个点的相同 pointNumber 和 pointIndex。这使得在将鼠标悬停在相应点上时无法显示与给定实例关联的正确信息。
这是一个可以在 Jupyter notebook 中运行的简化示例。最后我想在悬停时显示图像。
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) 检索的以下两个实例可以观察到该问题:
index feat1 feat2 label color
31 5.4 3.4 0 setosa
131 7.9 3.8 2 virginica
两者都分配了相同的 pointNumber 和 pointIndex,通过 print(HoverData) 检索:
{'points': [{'curveNumber': 2, 'pointNumber': 31, 'pointIndex': 31,'x': 7.9, 'y': 3.8, 'bbox': {'x0': 1235.5, 'x1': 1241.5, 'y0': 152.13,'y1': 158.13}}]}
{'points': [{'curveNumber': 0, 'pointNumber': 31,'pointIndex': 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 中特定类关联的实例。
这是一个错误还是我忽略了什么?非常感谢任何帮助!
最佳答案
事实证明,我错误地认为 pointNumber
和 pointIndex
是唯一的。一旦将非数字列用作 px.scatter()
中的 color
参数,每个类的点编号和索引就会重新编号。可以通过组合 curveNumber
和 pointNumber
和 pointIndex
之一来唯一标识散点图中的点。
一个潜在的解决方案是为每个类生成单独的索引并将它们添加到数据框中:
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]
关于python-3.x - Plotly Dash 散点图 : pointNumber is assigned to multiple points in hover data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70050831/
我是一名优秀的程序员,十分优秀!