代码之家  ›  专栏  ›  技术社区  ›  IVR

Dash:实现跟踪高亮回调

  •  0
  • IVR  · 技术社区  · 4 年前

    我有一个基本的dash应用程序,包括以下内容 app.py 文件:

    import dash
    import dash_core_components as dcc
    import dash_html_components as html
    import plotly.graph_objects as go
    
    def generate_plot():
        fig = go.Figure()
        fig.add_trace(go.Scatter(x=[1, 2, 3], y=[1, 2, 3], name="A", line={"width": 1}))
        fig.add_trace(go.Scatter(x=[1, 2, 3], y=[1, 3, 5], name="B", line={"width": 1}))
        return fig
    
    app = dash.Dash(__name__)
    app.layout = html.Div(children=[
        html.H1(children="title", className="title"),
        dcc.Graph(figure=generate_plot(), className="plot")
    ])
    

    我想在悬停时突出显示(将线宽增加到5)一条轨迹。到目前为止,我已经找到了一种在Jupyter笔记本中实现这一点的方法,方法是使用 go.FigureWidget 对象而不是 go.Figure (参见 this link 了解更多信息),但它在Dash中不起作用。如果有人对如何达到预期效果有任何想法,请告诉我们。

    非常感谢。

    0 回复  |  直到 4 年前
        1
  •  2
  •   IVR    4 年前

    我想我设法解决了一半的问题。

    首先,如果你使用一种方法来生成你的图形,你需要将其保存到一个单独的对象中:

    my_plot = generate_plot()
    

    其次,你需要给你的身材一个ID:

    dcc.Graph(figure=my_plot, id="my_plot")
    

    第三,你需要添加一个 app.callback 这样地:

    @app.callback(
        dash.dependencies.Output("my_plot", "figure"),
        [dash.dependencies.Input("my_plot", "hoverData")]
    )
    def highlight_trace(hover_data):
        # here you set the default settings
        for trace in my_pot.data:
            country["line"]["width"] = 1
            country["opacity"] = 0.5
        if hover_data:
            trace_index = hover_data["points"][0]["curveNumber"]
            my_plot.data[trace_index]["line"]["width"] = 5
            my_plot.data[trace_index]["opacity"] = 1
        return my_plot
    

    这将在悬停时突出显示跟踪,但只有当您悬停在另一个跟踪上时,它才会重置其状态(在某些情况下,这可能是预期的行为)。我还没有弄清楚如何在你没有悬停在跟踪外观上时重置它, 所以如果你对此有任何建议,请告诉我们,在那之前,我会认为这个问题没有答案

    编辑

    好的,我找到了重置悬停效果的方法:只需添加 clear_on_hover 参数如下: dcc.Graph(figure=my_plot, id="my_plot", clear_on_hover=True)

    非常感谢

    推荐文章
    pilu  ·  Plotly Dash API文档
    6 年前