You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Plotly.express绘制交互式柱状图时遇KeyError及ValueError问题求助

解决Plotly Express柱状图的KeyError和ValueError问题

问题分析

你原代码的核心问题是未正确处理value_counts()的返回结构,直接将Series的索引和值传入px.bar,导致Plotly无法识别对应字段;后续添加reset_index()后未正确构造数据源,引发真值判断歧义的错误。

修复后的代码

# 处理数据:将value_counts结果转为带明确列名的DataFrame
state_stats = df['state'].value_counts().head(10).reset_index()
state_stats.columns = ['state', 'count']  # 重命名列,便于Plotly识别

# 绘制交互式柱状图
bar_plot = px.bar(
    state_stats,
    x='state',
    y='count',
    text='count',  # 指定柱子上显示的数值为count列内容
    title='Top 10 states that have the most haunted places',
    labels={"y": "Count", "x": "States"}
)

bar_plot.update_traces(textfont_size=12, textposition='outside', cliponaxis=False)
bar_plot.show()

关键修复点

  • 数据结构调整:通过reset_index()将Series转为DataFrame,并手动命名列(state和count),让Plotly能直接读取数据源中的字段。
  • 参数匹配修正:px.bar的x、y、text参数直接对应DataFrame的列名,避免传入非列对象导致的识别错误。
  • 文本显示优化:将text参数指定为count列,确保柱子上显示正确的统计数值,替代原代码中无效的'1'。

内容的提问来源于stack exchange,提问作者Harsh Saharan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 12:24:55