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

如何基于宽格式DataFrame绘制堆叠柱状图并修复ufunc 'add'报错

问题根因与修复方案

直接报错原因

你在绘制最后一层Consumer Staples的堆叠柱时,bottom参数里错误加入了字符串'consumer staples',数值型的Series和字符串做加法运算触发了类型不匹配报错。

其他隐藏错误

  • 从第三层柱开始,height参数全部误写为Health_Care,会导致所有上层柱子高度完全错误
  • 堆叠底部bottom的累加逻辑错误:堆叠柱的底部应该是前面所有层的高度之和,你当前的计算多次把当前层高度也加进去了,最后一层还重复累加了两次Financials
  • frame.set_index('Seniority')执行后没有赋值给变量,属于无效代码

修正后完整代码

import numpy as np
import pandas as pd 
import matplotlib.pyplot as plt

data = {'Information Technology' : [217.88,  581.07,  247.28,  200.17], 'Industrials' : [142.33,  324.59,  159.60,  163.68], 'Health Care' : [126.63,  258.50,  135.77,  134.90], 'Communication' : [142.33,  324.59,  159.60,  163.68], 'Financials' : [212.54,  330.87,  165.56,  203.98], 'Consumer Staples' : [561.36,  390.29,  117.85,   93.67], 'Seniority' : [1.0, 2.0, 3.0, 4.0]}

frame = pd.DataFrame(data)
# 直接用列名取值更清晰,不需要用iloc
seniority = frame['Seniority']
it = frame['Information Technology']
ind = frame['Industrials']
health = frame['Health Care']
comm = frame['Communication']
fin = frame['Financials']
cons = frame['Consumer Staples']

# 逐层堆叠,bottom依次累加前面所有层的高度
plt.bar(seniority, it, 0.35, color='#FF0000', label="Information Technology") 
plt.bar(seniority, ind, 0.35, bottom=it, color='#ffff00', label="Industrials")
plt.bar(seniority, health, 0.35, bottom=it+ind, color='#0000FF', label="Health Care")
plt.bar(seniority, comm, 0.35, bottom=it+ind+health, color='#00FF00', label="Communication")
plt.bar(seniority, fin, 0.35, bottom=it+ind+health+comm, color='#FFA500', label="Financials")
plt.bar(seniority, cons, 0.35, bottom=it+ind+health+comm+fin, color='#800080', label="Consumer Staples")

# 坐标轴样式调整
for ticklabel in plt.gca().get_xticklabels():
    ticklabel.set_color('#CC3300') 
for ticklabel in plt.gca().get_yticklabels():
    ticklabel.set_color('#9932CC') 

plt.xlabel('Seniority')
plt.ylabel('Job Count')
# 调整图例位置避免超出画布
plt.legend(loc='upper right', bbox_to_anchor=(1.4, 1)) 
plt.title('Seniority and Job Count', size=20, fontweight="bold")

plt.show()

额外优化建议

其实pandas本身就封装了堆叠柱状图的绘制接口,不需要手动逐层计算bottom,代码可以简化为:

frame = pd.DataFrame(data).set_index('Seniority')
frame.plot(kind='bar', stacked=True, color=['#FF0000', '#ffff00', '#0000FF', '#00FF00', '#FFA500', '#800080'], width=0.35, figsize=(10,6))
# 后面直接接样式、坐标轴、标题设置即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 16:36:03