繁体   English   中英

当我运行相同的python代码但处于for循环中时,为什么matplotlib条形图会更改

[英]Why does my matplotlib bar diagram change when I am running the same python code but in a for-loop

相同的代码,但是用不同的方式编写的代码,给我不同的结果。

我想在matplotlib中绘制一个堆积的条。 当我不使用for循环时,它可以完美绘制。

plt.figure(figsize=(15,10))
plt.subplot(221)

plt.bar (prod_names, x[0], label=age_names[0])
plt.bar (prod_names, x[1], bottom=x[0], label=age_names[1])
plt.bar (prod_names, x[2], bottom=x[1] + x[0], label=age_names[2])
plt.bar (prod_names, x[3], bottom=x[2] + x[1] + x[0], label=age_names[3])
plt.bar (prod_names, x[4], bottom=x[3] + x[2] + x[1] + x[0], label=age_names[4])
plt.bar (prod_names, x[5], bottom=x[4] + x[3] + x[2] + x[1] + x[0], label=age_names[5])

plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

好吧:

好吧

但是,当我运行时:

plt.figure(figsize=(15,10))
plt.subplot(221)

for i in range(6):
    bottom = [0]*len(x[0])
    for j in range (i):
        bottom += x[j]
    plt.bar (prod_names, x[i], bottom, label=age_names[i])


plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

我坏了吧:

好吧

问题出在您的变量上,第三位是宽度,因此它使用bottom变量来确定条的宽度而不是其底部的高度。 因此,如果您仅更改以下行,它应该可以工作:

plt.bar(prod_names, x[i], bottom=bottom, label=age_names[i])

暂无
暂无

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

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