【问题标题】:Plotly-Dash: How to code interactive callbacks for hover functions in plotly dashPlotly-Dash:如何在 plotly dash 中为悬停函数编写交互式回调
【发布时间】:2021-02-25 05:35:02
【问题描述】:

是否可以在图表底部以破折号显示文本字段,以显示它们所在点的文本(将悬停数据显示为纯文本)。因此,当用户将鼠标悬停在某个点上时,文本框将能够进行更改。我已经定义了一个 dcc.Graph 组件和应用程序布局,但不确定如何定义悬停数据的回调函数。

我已经使用下面的代码来定义 dcc.Graph 和 app.layout

fig = go.Figure(data=plot_data, layout=plot_layout)

app.layout = html.Div([
    dcc.Graph(figure=fig),
    
        html.Div([
                    dcc.Markdown(id='mpg-metrics')
                ],style={'width':'20%','display':'inline-block'})
])

任何有关回调的帮助都会很棒。提前致谢

【问题讨论】:

    标签: python plotly plotly-dash plotly-python jupyterdash


    【解决方案1】:

    是的,这很有可能!由于您尚未提供设置的完整描述,因此我整理了一个最小示例,该示例利用了来自 dash.plotly.com/interactive-graphing 和 https://community.plotly.com/: Use Hover Trace As Input for Callback 的元素,其中描述了在回调中使用悬停数据。下面的代码 sn-p 将为 JupyterDash 生成以下应用程序。如果您想运行标准的 dash 应用程序,只需按照 these steps 重写它即可。

    我整理的解决方案应该完全符合您的目标。每次您将鼠标悬停在dcc.Graph 组件中图中一条线上的某个点上时,都会在其下方的html.Pre 组件中显示一组有关跟踪的详细信息,例如x 和y 值。试试看,让我知道它对你有什么效果!

    应用 1:

    如果您只想检索输出的某些元素,您可以像这样子集输出:

    json.dumps({'Date:':hoverData['points'][0]['x'],
                'Value:':hoverData['points'][0]['y']}, indent = 2)
    

    应用 2:

    JupyterDash,App1 的完整代码

    import json
    from textwrap import dedent as d
    import pandas as pd
    import plotly.graph_objects as go
    import numpy as np
    import dash
    import dash_core_components as dcc
    import dash_html_components as html
    import plotly.express as px
    from dash.dependencies import Input, Output
    from jupyter_dash import JupyterDash
    
    # app info
    app = JupyterDash(__name__)
    
    styles = {
        'pre': {
            'border': 'thin lightgrey solid',
            'overflowX': 'scroll'
        }
    }
    
    # data and basic figure
    x = np.arange(20)+10
    
    fig = go.Figure(data=go.Scatter(x=x, y=x**2, mode = 'lines+markers'))
    fig.add_traces(go.Scatter(x=x, y=x**2.2, mode = 'lines+markers'))
    
    app.layout = html.Div([
        dcc.Graph(
            id='basic-interactions',
            figure=fig,
        ),
    
        html.Div(className='row', children=[
            html.Div([
                dcc.Markdown(d("""
                  Click on points in the graph.
                """)),
                html.Pre(id='hover-data', style=styles['pre']),
            ], className='three columns'),
        ])
    ])
    
    
    @app.callback(
        Output('hover-data', 'children'),
        [Input('basic-interactions', 'hoverData')])
    def display_hover_data(hoverData):
        return json.dumps(hoverData, indent=2)
    
    app.run_server(mode='external', port = 8070, dev_tools_ui=True,
              dev_tools_hot_reload =True, threaded=True)
    

    JupyterDash、App2 的完整代码

    import json
    from textwrap import dedent as d
    import pandas as pd
    import plotly.graph_objects as go
    import numpy as np
    import dash
    import dash_core_components as dcc
    import dash_html_components as html
    import plotly.express as px
    from dash.dependencies import Input, Output
    from jupyter_dash import JupyterDash
    
    # app info
    app = JupyterDash(__name__)
    
    styles = {
        'pre': {
            'border': 'thin lightgrey solid',
            'overflowX': 'scroll'
        }
    }
    
    # data and basic figure
    y = np.arange(100)+10
    x = pd.date_range(start='1/1/2021', periods=len(y))
    
    fig = go.Figure(data=go.Scatter(x=x, y=y**2, mode = 'lines+markers'))
    fig.add_traces(go.Scatter(x=x, y=y**2.2, mode = 'lines+markers'))
    
    app.layout = html.Div([
        dcc.Graph(
            id='basic-interactions',
            figure=fig,
        ),
    
        html.Div(className='row', children=[
            html.Div([
                dcc.Markdown(d("""
                  Click on points in the graph.
                """)),
                html.Pre(id='hover-data', style=styles['pre']),
            ], className='three columns'),
        ])
    ])
    
    
    @app.callback(
        Output('hover-data', 'children'),
        [Input('basic-interactions', 'hoverData')])
    def display_hover_data(hoverData):
        try:
            return json.dumps({'Date:':hoverData['points'][0]['x'],
                               'Value:':hoverData['points'][0]['y']}, indent = 2)
        except:
            return None
    
    app.run_server(mode='external', port = 8070, dev_tools_ui=True,
              dev_tools_hot_reload =True, threaded=True)
    

    【讨论】:

    • 这可以工作。但不是像上图那样查看它,而是有一种方法只显示日期和值而不是曲线编号、点索引等。所以只显示 x 和 y 值
    • @vestland 嗨,vestland,想知道是否可以这样做,但不是悬停,而是 JSON 文本仅在您单击点时出现?
    猜你喜欢
    • 2021-06-07
    • 2021-08-10
    • 2021-05-22
    • 2020-03-07
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多