Plotly-Dash:如何为 plotly dash 中的悬停函数编写交互式回调 [英] Plotly-Dash: How to code interactive callbacks for hover functions in plotly dash

查看:89
本文介绍了Plotly-Dash:如何为 plotly dash 中的悬停函数编写交互式回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我使用下面的代码来定义 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'})])

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

解决方案

是的,这很有可能!由于您尚未提供对您的设置的完整描述,因此我整理了一个利用

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

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

应用 2:

JupyterDash、App1 的完整代码

导入jsonfrom textwrap import dedent as d将熊猫导入为 pd导入 plotly.graph_objects as go将 numpy 导入为 np导入破折号将 dash_core_components 导入为 dcc将 dash_html_components 导入为 html导入 plotly.express 作为 px从 dash.dependencies 导入输入,输出从 jupyter_dash 导入 JupyterDash# 应用信息app = JupyterDash(__name__)样式 = {'前':{'border': '细浅灰色实心','溢出X':'滚动'}}# 数据和基本图x = np.arange(20)+10fig = 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='基本交互',图=图,),html.Div(className='row', children=[html.div([dcc.Markdown(d(""";单击图中的点.""")),html.Pre(id='hover-data', style=styles['pre']),], className='三列'),])])@app.callback(输出('悬停数据','孩子'),[输入('基本交互','悬停数据')])def display_hover_data(hoverData):返回 json.dumps(hoverData, indent=2)app.run_server(mode='external', port = 8070, dev_tools_ui=True,dev_tools_hot_reload =真,线程=真)

JupyterDash、App2 的完整代码

导入jsonfrom textwrap import dedent as d将熊猫导入为 pd导入 plotly.graph_objects as go将 numpy 导入为 np导入破折号将 dash_core_components 导入为 dcc将 dash_html_components 导入为 html导入 plotly.express 作为 px从 dash.dependencies 导入输入,输出从 jupyter_dash 导入 JupyterDash# 应用信息app = JupyterDash(__name__)样式 = {'前':{'border': '细浅灰色实心','溢出X':'滚动'}}# 数据和基本图y = np.arange(100)+10x = pd.date_range(start='1/1/2021', period=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='基本交互',图=图,),html.Div(className='row', children=[html.div([dcc.Markdown(d(""";单击图中的点.""")),html.Pre(id='hover-data', style=styles['pre']),], className='三列'),])])@app.callback(输出('悬停数据','孩子'),[输入('基本交互','悬停数据')])def display_hover_data(hoverData):尝试:返回 json.dumps({'Date:':hoverData['points'][0]['x'],'值:':hoverData['points'][0]['y']}, indent = 2)除了:返回无app.run_server(mode='external', port = 8070, dev_tools_ui=True,dev_tools_hot_reload =真,线程=真)

Is it possible to have a text field at the bottom of a graph in dash that displays the text for the point they are on (showing hover data as plain text). So the text box will be able to make changes when users hover over a certain point. I have defined a dcc.Graph component and the app layout but am not sure how to define the callback function for the hoverdata.

I have used the below code to define dcc.Graph and 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'})
])

Any help with the callback will be great. thanks in advance

解决方案

Yes, that's very possible! Since you haven't provided a complete description of your setup, I've put together a minimal example that draws on elements from dash.plotly.com/interactive-graphing and https://community.plotly.com/: Use Hover Trace As Input for Callback that among other things describes the use of hover data in callbacks. The code snippet below will produce the following app for JupyterDash. If you'd like to run a standard dash app, just rewrite it following these steps.

The solution I've put together should do exactly what you're aiming for. Every time you hover over a point on one of the lines in the figure in the dcc.Graph component, a set of details about the trace is displayed in the html.Pre component under it, such as x and y values. Try it out and let me know how it works out for you!

App 1:

If you'd like to retrieve only certain elements of the output, you can subset the output like this:

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

App 2:

Complete code for 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)

Complete code for 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)

这篇关于Plotly-Dash:如何为 plotly dash 中的悬停函数编写交互式回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆