我正在使用带有日期列作为下拉列表的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)
答案 0 :(得分:1)
这是适合您的代码。
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)
答案 1 :(得分:0)
app = dash.Dash()
def createObject(x):
options = []
for i in x:
options.append({
'label': i,
'value': i
})
return options
df = pd.DataFrame({'message1': ['Hi', 'Bye', 'GN', 'Hi', 'Bye', 'GN'],
'date1': ['01/08/19', '01/08/19', '01/08/19', '02/08/19', '02/08/19', '02/08/19'],
'count1': [10, 20, 30, 15, 25, 35]})
app.layout = html.Div([
html.Br(),
html.Br(),
dcc.Dropdown(
id = 'first_dropdown',
options = createObject(df.date1.unique()),
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='value')]
)
def update_output_div(input_value):
return dcc.Graph(id = 'Bar_Plot',
figure = {
'data' : [
{'x':df[df['date1']==input_value].message1, 'y':df[df['date1']==input_value].count1, 'type':'bar', 'name':'First Chart'}
]
})
app.run_server(port=4050)
这对我有用