我使用csv文件作为我的数据源。我希望图表根据我选择的单选按钮进行更新,请在下面找到我的源代码。
import pandas as pd
import numpy as np
import plotly.graph_objs as go
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input,Output
df = pd.read_csv('population2.csv')
fst_yvalues = df['PopEstimate2010']/1000000
scd_yvalues = df['PopEstimate2011']/1000000
trd_yvalues = df['PopEstimate2012']/1000000
app = dash.Dash()
app.layout = html.Div(children=[
html.H1('My first Interactive Graph'),
html.Div(dcc.RadioItems(id='radio_items',
options=[{'label':'PopEstimate2010','value':'pop2010'},
{'label':'PopEstimate2011','value': 'pop2011'},
{'label':'PopEstimate2011' ,'value':'pop2012'}],
value='pop2010')),
html.Br(),
html.Div(children=[
dcc.Graph(id='int_bar')])])
@app.callback(Output('int_bar','figure'),[Input('radio_items','value')])
def bar_chart(value):
trace = []`
if value == 'pop2010':
trarce = [go.Bar(x=df['Name'],y=fst_yvalues)]
elif value == 'pop2011':
trarce = [go.Bar(x=df['Name'],y=scd_yvalues)]
else:
trarce = [go.Bar(x=df['Name'],y=trd_yvalues)]
layout = go.Layout(title='MY FIRST GRAPH',
xaxis=dict(title='MY X-AXIS'),
yaxis=dict(title='MY Y-AXIS'),hovermode='closest')
figure = go.Figure(data=trace,layout=layout)enter code here
return figure
if __name__ == '__main__':
app.run_server(debug=True)
当我尝试运行此命令时,它只会为我提供布局,而不能提供实际的图形。
答案 0 :(得分:0)
下面是我要使其正常工作的方法:
@app.callback(Output('int_bar','figure'),[Input('radio_items','value')])
def make_bar_chart(value):
if value == 'pop2010':
figure = {'data': [go.Bar(x=df['Name'],y=fst_yvalues)],
'layout': go.Layout(title='MY FIRST GRAPH',
xaxis=dict(title='MY X-AXIS'),
yaxis=dict(title='MY Y-AXIS'),hovermode='closest')
}
...
...
return figure
if __name__ == '__main__':
app.run_server(debug=True)