matplotlib 堆叠柱状图 AssertionError:不兼容的大小:参数 'bottom' 必须为长度 3 或标量

6 投票
1 回答
15139 浏览
提问于 2025-04-18 03:33

我需要制作一个柱状图,展示不同的列表,像这样:

import math
import numpy as np
import matplotlib.pyplot as plt


month=["dec-09","jan","feb"]
n=len(month)
kitchen=[57.801,53.887,49.268]
laundry=[53.490,56.568,53.590]
air=[383.909,395.913,411.714]
other=[519.883,483.293,409.956]

ind=np.arange(n)
width=0.35

p1=plt.bar(ind,kitchen,width,color="cyan")
p2=plt.bar(ind,laundry,width,color="red",bottom=kitchen)
p3=plt.bar(ind,air,width,color="green",bottom=kitchen+laundry)
p4=plt.bar(ind,other,width,color="blue",bottom=kitchen+laundry+air)

plt.ylabel("KWH")
plt.title("winter")
plt.xticks(ind+width/2,("dec-09","jan","feb"))
plt.show()

这只是一个简单的代码,我想把它们叠加起来,但我遇到了一个错误,不知道该怎么解决。

p3=plt.bar(ind,air,width,color="green",bottom=kitchen+laundry)
File "C:\Python33\lib\site-packages\matplotlib\pyplot.py", line 2515, in bar
ret = ax.bar(left, height, width=width, bottom=bottom, **kwargs)
File "C:\Python33\lib\site-packages\matplotlib\axes.py", line 5007, in bar
nbars)
AssertionError: incompatible sizes: argument 'bottom' must be length 3 or scalar

1 个回答

11

创建 kitchenlaundryairother 这几个 NumPy 数组:

import math
import numpy as np
import matplotlib.pyplot as plt


month=["dec-09","jan","feb"]
n=len(month)
kitchen=np.array([57.801,53.887,49.268])
laundry=np.array([53.490,56.568,53.590])
air=np.array([383.909,395.913,411.714])
other=np.array([519.883,483.293,409.956])

ind=np.arange(n)
width=0.35

p1=plt.bar(ind,kitchen,width,color="cyan")
p2=plt.bar(ind,laundry,width,color="red",bottom=kitchen)
p3=plt.bar(ind,air,width,color="green",bottom=kitchen+laundry)
p4=plt.bar(ind,other,width,color="blue",bottom=kitchen+laundry+air)

plt.ylabel("KWH")
plt.title("winter")
plt.xticks(ind+width/2,("dec-09","jan","feb"))
plt.show()

在这里输入图片描述


你遇到的错误是因为把 lists 相加时,是把它们拼接在一起:

In [162]: [1,2,3] + [4,5,6]
Out[162]: [1, 2, 3, 4, 5, 6]

而 NumPy 数组相加时,是逐个元素相加:

In [163]: np.array([1,2,3]) + np.array([4,5,6])
Out[163]: array([5, 7, 9])

错误出现在这一行:

p3=plt.bar(ind,air,width,color="green",bottom=kitchen+laundry)

因为 kitchen+laundry 变成了6个元素(因为是拼接),而你其实只想要3个元素(在逐个元素相加之后)。

撰写回答