Plotly Dash如何实现无下拉选项选中时不显示图表?
Dash数据看板空选状态解决方案
核心问题原因
下拉框清空后返回的selected_country值为None,此时用空值筛选DataFrame会得到空结果,后续调用iloc[0]取数时触发索引越界错误。
修改步骤
- 调整下拉框默认值为
None,实现首次启动无选中效果 - 回调函数开头增加空值判断,无选中时直接返回空图表,跳过后续取数逻辑
- 修正代码中被HTML转义的双引号
完整修改后代码
import pandas as pd import dash import dash_html_components as html import dash_core_components as dcc from dash.dependencies import Input, Output import plotly.express as px import plotly.graph_objects as go df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv') fig = go.Figure() # 创建Dash应用 app = dash.Dash() # 配置应用布局 app.layout = html.Div(children=[ html.H1(children='人口统计数据看板'), dcc.Dropdown(id='country-dropdown', options=[{'label': x, 'value': x} for x in df.country.unique()], value=None, # 修改默认值为空,实现首次启动无选中 multi=False, clearable=True), dcc.Graph(id='indicators', figure=fig) ]) # 配置回调函数 @app.callback( Output('indicators', 'figure'), [Input('country-dropdown', 'value')]) def display_demographic_statistics(selected_country): # 新增空值判断:无选中国家时直接返回空图表 if not selected_country: return go.Figure() filtered_country = df[df.country == selected_country] pop_confirmed = df.loc[df['country'] == selected_country, 'pop'].iloc[0] lifexp = df.loc[df['country'] == selected_country, 'lifeExp'].iloc[0] average_confirmed = df["pop"].mean() average_lifexp = df["lifeExp"].mean() return { 'data': [go.Indicator( mode='number+delta', value=pop_confirmed, delta={'reference': average_confirmed, 'position': 'right', 'valueformat': ',g', 'relative': False, 'font': {'size': 15}}, number={'valueformat': ',', 'font': {'size': 20}, }, domain={'y': [0, 1], 'x': [0, 1]})], 'layout': go.Layout( title={'text': '人口统计指标'}, grid = {'rows': 2, 'columns': 2, 'pattern': "independent"}, template = {'data' : {'indicator': [{ 'mode' : "number+delta+gauge", 'delta' : {'reference': 90}}]}} ), } # 启动本地服务 if __name__ == '__main__': app.run_server(debug=True, use_reloader=False)
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

