Streamlit中Plotly堆叠条形图无法显示的问题排查
PlotlyError 错误排查与修复
核心问题定位
你的代码中第二个图表的fig_4定义末尾多了一个逗号:
fig_4 = px.bar(... text_auto=True),
这个逗号会把fig_4变成一个元组(格式为(Figure对象,)),而st.plotly_chart()要求传入的必须是dict、list或Plotly的Figure实例,元组不符合要求,因此触发了PlotlyError。
修复步骤
直接删掉fig_4赋值语句末尾的逗号即可,修复后的代码片段:
with col20: df_3 = data_2.groupby(["label","extra_author_attributes.gender"]).size().reset_index(name='counts') fig_4 = px.bar(df_3, x="extra_author_attributes.gender", y="counts", color="label", labels={ "label": "Sentiment", "counts": "Count", "extra_author_attributes.gender": "Gender" }, text_auto=True) # 移除了末尾多余的逗号 st.plotly_chart(fig_4)
额外优化建议
- 没必要创建20列来实现两个图表并排,用
st.columns(2)更简洁高效:
col_left, col_right = st.columns(2) with col_left: # 第一个堆叠条形图代码 with col_right: # 第二个堆叠条形图代码
df_2和df_3的分组逻辑完全一致,可以复用同一个DataFrame,减少重复计算:
# 只计算一次分组统计 df_gender_sentiment = data_2.groupby(["label","extra_author_attributes.gender"]).size().reset_index(name='counts') # 第一个图表用这个df fig_3 = px.bar(df_gender_sentiment, x="label", y="counts", ...) # 第二个图表也用这个df fig_4 = px.bar(df_gender_sentiment, x="extra_author_attributes.gender", ...)
内容的提问来源于stack exchange,提问作者zadam
相关产品推荐
相关产品推荐

