【问题标题】:Plotly: How to edit text output based on value retrieved by hovering?Plotly:如何根据悬停检索的值编辑文本输出?
【发布时间】:2020-05-18 19:31:53
【问题描述】:

我正在使用下面的代码在 plotly dash 上显示 x 和 y 值。但后来我希望能够在 "value" 文本字段下方添加另一个文本字段。

文本字段将被称为“Category”,因此如果显示的 y 值是: 5k 那么类别 = 不贵,或者如果价值是 20k 那么类别 = 平均价格,如果价值是 30k 然后类别 = 太贵了。

我将如何实现这一点?这是显示悬停在上面的值的运行代码

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)

【问题讨论】:

    标签: python plotly plotly-dash plotly-python


    【解决方案1】:

    对您的设置进行以下修改:

        if hoverData['points'][0]['y'] >= 5000:
            Category = 'not Pricey'
        if hoverData['points'][0]['y'] >= 20000:
            Category = 'average price'
        if hoverData['points'][0]['y'] >= 30000:
            Category = 'Too pricey'
        
        output = json.dumps({'Date:':hoverData['points'][0]['x'],
                             'Value:':hoverData['points'][0]['y'],
                             'Category':Category
                            }, indent = 2)
    

    ... 下面的代码 sn-p 生成以下应用程序:

    您没有为低于 5000 的值指定类别,所以现在只返回一个空字符串。试一试,让我知道这对你有什么影响。

    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)+20
    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'),
        ])
    ])
    
    
    # The text field would be called "Category" so that if the y value displayed is:
    # 5k then category = not pricey or if value is 20k then category = average price and
    # if value is 30k then category = too pricey.
    
    @app.callback(
        Output('hover-data', 'children'),
        [Input('basic-interactions', 'hoverData')])
    def display_hover_data(hoverData):
        global hd
        hd = hoverData
        Category = ''
        try:
            output = json.dumps({'Date:':hoverData['points'][0]['x'],
                               'Value:':hoverData['points'][0]['y']}, indent = 2)
            
            if hoverData['points'][0]['y'] >= 5000:
                Category = 'not Pricey'
            if hoverData['points'][0]['y'] >= 20000:
                Category = 'average price'
            if hoverData['points'][0]['y'] >= 30000:
                Category = 'Too pricey'
            
            output = json.dumps({'Date:':hoverData['points'][0]['x'],
                                 'Value:':hoverData['points'][0]['y'],
                                 'Category':Category
                                }, indent = 2)
            
            print(output)
            return output
    
                
        except:
            return None
    
    app.run_server(mode='external', port = 8070, dev_tools_ui=True,
              dev_tools_hot_reload =True, threaded=True)
    

    【讨论】:

      猜你喜欢
      • 2020-09-20
      • 2012-11-01
      • 2022-01-09
      • 2021-07-08
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 2018-06-25
      相关资源
      最近更新 更多