简体   繁体   English

Matplotlib-堆积的条形图,底部

[英]Matplotlib - Stacked Bar Chart, bottoms

I'm struggling to understand why my stacked bar graph in matplotlib isn't behaving correctly. 我正在努力了解为什么我在matplotlib中堆积的条形图的行为不正确。 It has to do with the 'bottom' argument in my plt.bar() function 它与我的plt.bar()函数中的“底部”参数有关

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: 每个列表中只有1个项目:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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