Matplotlib – Stacked Bar Chart, bottoms

Question:

I’m struggling to understand why my stacked bar graph in matplotlib isn’t behaving correctly. It has to do with the ‘bottom’ argument in my plt.bar() function

If I hard code the values I want to plot, everything works correctly:

import matplotlib.pyplot as plt

var1 = 'Bar1' 
var2 = .2403 
var3 = .1256
var4 = .1158

plt.bar(var1, var2, color='green')
plt.bar(var1, var3, bottom=var2, color='blue')
plt.bar(var1, var4, bottom=(var2+var3), color='red')

Here is the correct output and what it should look like: enter image description here

In my code I have a function that generates some values that are in a list and I will iteratively plot these. Here is what the values look like after doing some math. There is only 1 item in each list:

var1 = 'Bar1'
var2 = [.2403]
var3 = [.1256]
var4 = [.1158]

And now I try to use the same code to plot these:

plt.bar(var1, var2, color='green')
plt.bar(var1, var3, bottom=var2, color='blue')
plt.bar(var1, var4, bottom=(var2+var3), color='red')

But the result does not look right. I am not sure what is happening here:
enter image description here

Asked By: Erich Purpur

||

Answers:

thanks to the comment above I have a solution:

for i in range(0, len(var1)):
    plt.bar(var1, var2, color='green')
    plt.bar(var1, var3, bottom=var2[i], color='blue')
    plt.bar(var1, var4, bottom=(var2[i]+var3[i]), color='red')
Answered By: Erich Purpur

The addition operator does not add the values in two lists together, but merges them together into one list. To sum the values in two lists together, you must use the sum function in addition to +.

var1 = 'Bar1'
var2 = [.2403]
var3 = [.1256]
var4 = [.1158]

plt.bar(var1, var2, color='green')
plt.bar(var1, var3, bottom=var2, color='blue')
plt.bar(var1, var4, bottom=sum(var2+var3), color='red')
Answered By: Amir Hossein
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.