首页 > 解决方案 > Python Dash Plotly:在悬停时显示默认最接近的数据或在图表中比较悬停时的数据

问题描述

我正在使用 Dash Plotly 构建一个简单的应用程序。
默认设置是图表“比较悬停时的数据”。 我想将默认设置更改为“在悬停时显示最接近的数据”:
在此处输入图像描述

在此处输入图像描述

如何在下面的代码中做到这一点?

import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash(__name__)

app.layout = html.Div(children=[
    html.H1(children='Hello New Other Change', ),

    html.Div(children='''
        Dash: A web application framework for Python.
    '''),

    dcc.Graph(
        id='example-graph',
        figure={
            'data': [
                {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
                {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},
            ],
            'layout': {
                'title': 'Dash Data Visualization',
            }
        }
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)

标签: pythonplotlyplotly-dash

解决方案


可以通过在图中添加 hovermode 来将图表默认设置为在 plotly dash 中显示最接近的数据,如下所示:

figure={
    'data': [
        {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
        {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},
    ],
    'layout': {
        'hovermode': 'closest',
    }
}

通过以下方式设置图表默认值以比较数据

'layout': {
    'hovermode': 'compare',
}

推荐阅读