【发布时间】:2017-11-24 18:03:52
【问题描述】:
我想在 2 个堆叠条形图中(并排)显示一些数据。使用 matplotlib。
keys=['BF', 'VL', 'GM', 'VM']
data=[[0.10992407597195027, 0.084754817342900857],
[0.20119173770112833, 0.24308696457787043],
[0.49912704691619575, 0.53468456580435009],
[0.18975713941072578, 0.13747365227487865]]
x = range(2)
f, ax1 = plt.subplots(1, figsize=(10,5))
plt.bar(x,data[0], label=keys[0])
plt.bar(x,data[1], bottom=data[0], label=keys[1])
plt.bar(x,data[2], bottom=data[1], label=keys[2])
plt.bar(x,data[3], bottom=data[2],label=keys[3])
plt.legend(loc='upper left')
plt.show()
在我看来,红色条 (VM) 没有堆叠在其余条的顶部,导致图形看起来很奇怪(尽管我指定了正确的 bottom 属性。每个中的数据bar 的总和应该正好是 1。我该如何解决这个问题?
编辑:
我能够通过使用以下相当混乱的代码将bottom 属性设置为下栏的总和,而不仅仅是明确的下栏,从而解决了这个问题:
plt.bar(x,data[0], width = bar_width, label=keys[0])
plt.bar(x,data[1], width = bar_width, bottom=data[0], label=keys[1])
plt.bar(x,data[2], width = bar_width, bottom=[data[0][i]+data[1][i] for i in x], label=keys[2])
plt.bar(x,data[3], width = bar_width, bottom=[data[0][i]+data[1][i]+data[2][i] for i in x],label=keys[3]
有没有更好的方法来做到这一点?条形越多,它就不能很好地扩展。
【问题讨论】:
标签: python python-2.7 matplotlib bar-chart data-visualization