gpt4 book ai didi

python - matplotlib 堆叠条形图 AssertionError : incompatible sizes: argument 'bottom' must be length 3 or scalar

转载 作者:太空狗 更新时间:2023-10-29 22:16:00 25 4
gpt4 key购买 nike

我需要像这样想出不同列表的条形图

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

最佳答案

创建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()

enter image description here


您得到的错误是由于添加 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 个元素(在元素加法之后)。

关于python - matplotlib 堆叠条形图 AssertionError : incompatible sizes: argument 'bottom' must be length 3 or scalar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23189815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com