Streamlit中使用multiselect实现多选折线图失败问题求助
解决Streamlit multiselect配合Plotly折线图不显示的问题
嗨,我之前也碰到过一模一样的问题!核心原因很简单:st.multiselect返回的是选中项的列表,而不是单个字符串,你原来用df['country'] == country的方式只能匹配单个国家,自然筛选不到数据,图表就空了。
直接给你修改好的可运行代码:
import streamlit as st import pandas as pd import plotly.express as px df = pd.DataFrame(px.data.gapminder()) def plot(): clist = df['country'].unique() # 替换为multiselect,可设置默认选中项提升体验 selected_countries = st.multiselect('Select countries', clist, default=['China', 'United States']) # 处理空选择的情况,避免空图表或报错 if not selected_countries: st.warning('请至少选择一个国家') return st.header('你选择了:' + ', '.join(selected_countries)) # 用isin()匹配列表中的所有国家,替代原有的==逻辑 filtered_df = df[df['country'].isin(selected_countries)] # Plotly会自动根据country列分组生成多条折线 fig = px.line(filtered_df, x="year", y="gdpPercap", color="country", title='多国家GDP人均变化对比') st.plotly_chart(fig) plot()
关键修改点说明:
- 组件返回值适配:把变量名改成
selected_countries(更贴合列表类型),st.multiselect支持多选,还能通过default参数设置默认选中项,让用户打开页面就能看到效果。 - 筛选逻辑修正:用
df['country'].isin(selected_countries)代替原来的==,这样能匹配列表里的所有国家,正确筛选出需要的数据。 - 空选择容错:添加了
if not selected_countries的判断,当用户没选任何国家时显示提示,避免出现空图表或者潜在报错。 - 图表体验优化:给
px.line加上color="country"参数,让Plotly自动按国家区分折线颜色,同时更新标题为对比主题,展示逻辑更清晰。
内容的提问来源于stack exchange,提问作者Lens
相关产品推荐
相关产品推荐

