# Stacked barchart, bottom parameter triggers Error: Shape mismatch: objects cannot be broadcast to a single shape

I am working in python3 and I want to obtain a stacked barchart plot, showing three different variables on 5 different columns. My code works fine if I do not add the 'bottom parameter' in plt.bar (but I need to, in order for the stacks to appear in the correct order):

import numpy as np
import matplotlib as plt

columns=['a','b','c','d','e']
pos = np.arange(5)
var_one=[40348,53544,144895,34778,14322,53546,33623,76290,53546]
var_two=[15790,20409,87224,22085,6940,27099,17575,41862,27099]
var_three=[692,3254,6645,1237,469,872,569,3172,872]

plt.bar(pos,var_one,color='green',edgecolor='green')
plt.bar(pos,var_two,color='purple',edgecolor='purple')
plt.bar(pos,var_three,color='yellow',edgecolor='yellow')
plt.xticks(pos, columns)
plt.show()


However, once I add the bottom parameter in bar.plot (as shown below):

import numpy as np
import matplotlib as plt

columns=['a','b','c','d','e']
pos = np.arange(5)
var_one=[40348,53544,144895,34778,14322,53546,33623,76290,53546]
var_two=[15790,20409,87224,22085,6940,27099,17575,41862,27099]
var_three=[692,3254,6645,1237,469,872,569,3172,872]

plt.bar(pos,var_one,color='green',edgecolor='green')
plt.bar(pos,var_two,color='purple',edgecolor='purple',bottom=var_one)
plt.bar(pos,var_three,color='yellow',edgecolor='yellow',bottom=var_one+var_two)
plt.xticks(pos, columns)
plt.show()


the code triggers the error

ValueError: shape mismatch: objects cannot be broadcast to a single shape


How could I fix it?

if you change your code to the following:

import numpy as np
import matplotlib.pyplot as plt

columns = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j']
pos = np.arange(9)
var_one = np.array([40348, 53544, 144895, 34778, 14322, 53546, 33623, 76290, 53546])
var_two = np.array([15790, 20409, 87224, 22085, 6940, 27099, 17575, 41862, 27099])
var_three = np.array([692, 3254, 6645, 1237, 469, 872, 569, 3172, 872])

plt.bar(pos, var_one, color='green', edgecolor='green')
plt.xticks(pos, columns)
plt.show()


The result will be like this:

• Just by adding its value to the values of two other categories at the respective column. in this case you the yticks are not meaningful – Alireza Zolanvari Mar 14 at 12:02
• The code was modified. Is it what you want? – Alireza Zolanvari Mar 14 at 12:14
• I see now, thank you, I thought I had to use another parameter. For people who will look up this page in the future: number of columns does not need to be changed to 9, can be any number you need it to be. – Camilla Mar 14 at 13:03
• feel free to edit my answer – Alireza Zolanvari Mar 14 at 13:09

The error was caused by the fact that you tried to use + between two arrays, which is concatenation. If you had done:

plt.bar(pos, var_one, color='green', edgecolor='green')
plt.bar(pos, var_two, color='purple', edgecolor='purple', bottom=var_one)