【问题标题】:Callback function not using the source file to update the graph回调函数不使用源文件更新图形
【发布时间】:2019-01-21 13:06:25
【问题描述】:

我使用 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)

当我尝试运行它时,它只给了我布局而不是实际的图表。

【问题讨论】:

  • 我建议逐行运行您的代码...并尝试查看添加了哪个按钮和标签的位置.....尝试不使用 RadioItems 的代码,然后尝试保存而不是打印文件为 JPEG 或 PNG,只是为了查看中间输出
  • 我在没有单选按钮的情况下试过这个,它工作正常,图表被绘制出来。使用单选按钮的回调函数时会出现问题...
  • @PuneetSinha,感谢您的评论和建议。我通过删除'traces'和'Figure'对象调用让它工作。我为每个满足的条件构建了一个完整的“数字”,然后返回了那个数字。
  • 感谢您的支持 :) ... 干杯

标签: pandas plotly plotly-dash


【解决方案1】:

以下是我为使其工作而采取的方法:

  @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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-02
    • 1970-01-01
    • 2023-01-18
    • 2015-09-11
    • 2017-03-01
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    相关资源
    最近更新 更多