The same code, but written in different ways, gives me different results.
I want to draw a stacked bar in matplotlib. And it draws perfectly when I do not use for-loop.
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.)
Good bar:
But, when I run:
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.)
I get bad bar:
The issue is with your variable, the third place is for width, so it is using your bottom
variable to decide the widths of the bars instead of the height of their bases. So if you just change the following line it should work:
plt.bar(prod_names, x[i], bottom=bottom, label=age_names[i])
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.