Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib stacked bar chart AssertionError: incompatible sizes: argument 'bottom' must be length 3 or scalar

I required to come up with a bar chart of different list like so

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

it's just a simple code that I would like to stack them up but I encountered an error and I don't know what to do about it

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
like image 483
user3555206 Avatar asked Apr 21 '14 02:04

user3555206


1 Answers

Make kitchen, laundry, air and other NumPy arrays:

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


The error you were getting is due to fact that adding lists concatenates them:

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

whereas, adding NumPy arrays adds the arrays element-wise:

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

The error was being raised on the line:

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

because kitchen+laundry had 6 elements (because of concatenation), when you wanted just 3 elements (after element-wised addition).

like image 181
unutbu Avatar answered Nov 15 '22 08:11

unutbu