简体   繁体   中英

Matplotlib - Stacked Bar Chart, bottoms

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: 在此处输入图片说明

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: 在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM