首页 > 解决方案 > 有下拉菜单时在破折号中设置 hover_data

问题描述

我正在尝试做一些与他们在示例教程中所做的非常相似的事情。我现在唯一要添加的是在悬停时显示其他数据值。

我的代码如下所示:

df = pd.DataFrame({
     'ids': [0, 0, 1, 1, 2, 2],
     'er1': [0, 0, 3, 3, 4, 4],
     'er2': [3, 3, 2, 2, 5, 5],
     'ranking1': [1, 1, 2, 2, 3, 3],
     'ranking2': [2, 2, 1, 1, 3, 3],
     'time': [0, 1, 0, 1, 0, 1],
     'vals': [0, 1, 4, 5, 2, 7]})


app.layout = html.Div([
    html.Div([
        dcc.Dropdown(
            id='crossfilter-axis',
            options=[{'label':i,'value':i} for i in ['Errors','Rankings']],
            value='Errors'
        )], style = {'width':'99%', 'display': 'inline-blocks'}),
    html.Div([
        dcc.Graph(
            id='crossfilter-indicator-scatter',
            hoverData={'points': [{'customdata': 0}]}
        )
    ], style={'width':'99%', 'display':'inline-block', 'padding':'0.20'}),
    html.Div([
        dcc.Graph(id='x-time-series'),
    ], style={'display':'inline-block','width':'99%'})
])


@app.callback(
    dash.dependencies.Output('crossfilter-indicator-scatter', 'figure'),
    [dash.dependencies.Input('crossfilter-axis','value')])
def update_graph(axis_name):
    dfff = df[df['time']==0]
    if axis_name == 'Errors':
        fig = px.scatter(dfff,x='er1',y='er2',hover_name = 'ids',hover_data={'er1':True,'er2':True,'ranking1':True,'ranking2':True})
    else:
        fig = px.scatter(dfff,x='ranking1',y='ranking2',hover_name='ids',hover_data={'er1':True,'er2':True,'ranking1':True,'ranking2':True})

    fig.update_layout(font= dict(size=20),hovermode='closest')

    #This is line I think causes the problem, but I don't know to solve it.
    fig.update_traces(customdata= dfff['ids'])

    return fig


def create_time_series(dff):
    fig = px.scatter(dff, x='time',y='vals')
    fig.update_traces(mode='lines+markers')
    fig.update_layout(font=dict(size=20))

    return fig


@app.callback(
    dash.dependencies.Output('x-time-series', 'figure'),
    [dash.dependencies.Input('crossfilter-indicator-scatter', 'hoverData')])
def update_x_timeseries(hoverData):
    print(hoverData['points'][0])
    id_m = hoverData['points'][0]['customdata']
    dff = df[df['ids']==id_m]
    return create_time_series(dff)


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

这很好用,只是它没有显示所有的 hover_data。它显示了这一点: 显示绘图 hover_data 的图像

即: %{customdata[0]} 而不是实际值。有谁知道如何解决这个问题?谢谢。

标签: pythonplotlyplotly-dash

解决方案


推荐阅读