首页 > 解决方案 > 使用 Dash 制作带有 2 列和日期列的交互式条形图作为下拉列表?

问题描述

我正在使用带有日期列的 Dash 作为下拉列表制作条形图。如果用户更改日期下拉列表,这将是一个交互式图表。

以下是示例数据框:

message  Date     Count
Hi       01/08/19   10
Bye      01/08/19   20
GN       01/08/19   30
Hi       02/08/19   15
Bye      02/08/19   25
GN       02/08/19   35

以下是我当前的代码。我是第一次使用 Dash,所以有一些错误。

app = dash.Dash()

app.layout = html.Div([

    dcc.Dropdown(
        id = 'first_dropdown',
        options = df.Date,
        placeholder='Select a Date'
    )
    html.Div(id='output-graph')

])

@app.callback(
    Output(component_id='output-graph', component_property='children'),
    [Input(component_id='first_dropdown', component_property='options')]
)


    return dcc.Graph(id = 'Bar_Plor', 
                  figure = {
                      'data' : [
                          {'x':df.message, 'y':df.count, 'type':'bar', 'name':'First Chart'}
                          ]
                      })


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

标签: pythonplotlyplotly-dash

解决方案


这是一个适合您的代码。

import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output



app = dash.Dash()
df = pd.DataFrame({'message': ['Hi', 'Bye', 'GN', 'Hi', 'Bye', 'GN'],
                   'Date': ['01/08/19', '01/08/19', '01/08/19', '02/08/19', '02/08/19', '02/08/19'],
                   'Count': [10, 20, 30, 15, 25, 35]})
app.layout = html.Div([

    dcc.Dropdown(
        id = 'first_dropdown',
        options = df.Date,
        placeholder='Select a Date'
    ),
    html.Div(id='output-graph')

    ])

@app.callback(
    Output(component_id='output-graph', component_property='children'),
    [Input(component_id='first_dropdown', component_property='options')]
    )

def update_output_div(input_value):
    return dcc.Graph(id = 'Bar_Plor',
                  figure = {
                      'data' : [
                          {'x':df.message, 'y':df.Count, 'type':'bar', 'name':'First Chart'}
                          ]
                      })


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


推荐阅读