将短划线下拉选择传递给Variab

2024-05-16 03:31:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我在获取参数以继承仪表板中的用户下拉选择时遇到问题。你知道吗

下面是我代码的三个部分。我不认为问题出在布局/图形部分,因为如果我删除Dropdown对象并显式地分配boro变量(即取消对第1部分中第一行的注释),我就能够得到要填充的图形。此外,如果我在没有图形的情况下进行测试,并且只尝试打印变量值,那么在使用下拉列表时它仍然显示为空。你知道吗

有人能帮忙吗?我正在学习Plotly破折号教程(https://dash.plot.ly/dash-core-components/dropdown)中给出的示例,但我不确定是否正确地翻译了它们。你知道吗

第1部分:从API获取数据

#boro = 'Bronx'
def getHealth(boro):
    health_url = ('https://data.cityofnewyork.us/resource/nwxe-4ae8.json?' +\
            '$select=health,count(tree_id)' +\
            '&$where=boroname=\'' + boro + '\'' +\
            '&$group=health').replace(' ', '%20')
    health_trees = pd.read_json(health_url)

def getStew(boro):
    stew_url = ('https://data.cityofnewyork.us/resource/nwxe-4ae8.json?' +\
            '$select=steward,health,count(tree_id)' +\
            '&$where=boroname=\'' + boro + '\'' +\
            '&$group=steward,health').replace(' ', '%20')
    stew_trees = pd.read_json(stew_url)

第2部分:设置布局,创建图形

app.layout = html.Div(children=[
    html.H1(children='Trees Overview'),

    html.Div(children='''
        HEALTH QUALITY
    '''),
    dcc.Dropdown(
        id='dropdown',
        options=[{'label': i, 'value': i} for i in trees.boroname.unique()],
        value='Bronx',
        clearable=False
    ),
    html.Div(id='table-container'),
])

def generateGraphs(df1,df2,df3):
    return dcc.Graph(
        id='graph1',
        figure={
            'data': [
                go.Pie(labels=df1['health'],values=df1['count_tree_id']),
            ],
            'layout': {
                'title': 'Count By Species'
            }
        }
    ),

    dcc.Graph(
        id='graph2',
        figure={
            'data': [
                go.Bar(x=df2[df2['steward']==i]['health']
                       ,y=df2[df2['steward']==i]['count_tree_id']
                       ,name=i
                       ,marker=go.bar.Marker(
                    color='rgb(26, 118, 255)'
                ))
                for i in df3['steward'].unique()
            ]
        }
    )

第三部分:我认为问题就出在这里。我是否正确地使用了@app.callback函数?我是否正确地定义了retHealth()并调用了generateGraphs()?你知道吗

@app.callback(
    dash.dependencies.Output('table-container', 'children'),
    [dash.dependencies.Input('dropdown', 'value')])
def retHealth(value):
    health=getHealth(value)
    stew=getStew(value)
    return generateGraphs(health,stew,trees)

Tags: idjsontree图形urldatavaluedef