不产生多个输出的Dash回调



我试图在一个回调中执行以下操作:

  1. 根据URL
  2. 将用户路由到正确的布局(page_1_layout或page_2_layout)
  3. 同时,根据URL更新数据框和相关图形(其思想是URL参数将有助于过滤数据框并生成相关可视化)。

根据Dash文档,回调可以产生多个输出。在本例中,我试图生成正确的布局(输出#1)并更新图形(输出#2)。我也尝试过使用数据框作为输出,但这需要数据框是全局的。

下面是布局代码:

app.layout = html.Div([
dcc.Location(id='url', refresh=False),
html.Div(id='page-content')
])

index_page = html.Div([
dcc.Link('Go to Page 1', href='/CA'),
html.Br(),
dcc.Link('Go to Page 2', href='/WY'),
])
page_1_layout = html.Div([
html.H1('Page 1'),
html.Div(id='page-1-content'),
dcc.Graph(id='graph-output'),
html.Br(),
dcc.Link('Go to Page 2', href='/WY'),
html.Br(),
dcc.Link('Go back to home', href='/'),
])

下面是回调代码:

@app.callback(Output('page-content', 'children'), Output('graph-output', 'figure'), [Input('url', 'pathname')])
def display_page(pathname):
pathname = str(pathname)
if pathname.startswith('/CA'):
country = pathname.split('/')[-1]
print(country)
dff = df.loc[df['state'] == country.lower()]
print(dff)
fig = px.pie(dff, values='median_listing_price', names="state", title="xxx")
return page_1_layout, fig

elif pathname == '/WY':
country = pathname.split('/')[-1]
print(country)
dff = df.loc[df['state'] == country.lower()]
print(dff)

return page_2_layout, fig

else:
return index_page, fig

这是错误信息:

在Dash回调的Output中使用了一个不存在的对象。该对象的id为"graph-output",属性为"figure"。当前布局中的字符串>id为:[url, page-content]

我已经在回调中指定了额外的输出,所以我想知道为什么它不识别它?

问题是graph-output组件在页面布局呈现之前不存在。这个问题的一个解决方案是将图形作为布局的一部分呈现,例如,像这样,

def render_graph():
# Put your graph logic here.
return dcc.Graph(id='graph-output')

def page_1_layout():
return html.Div([
html.H1('Page 1'),
html.Div(id='page-1-content'),
render_graph(),
html.Br(),
dcc.Link('Go to Page 2', href='/WY'),
html.Br(),
dcc.Link('Go back to home', href='/'),
])

最新更新