【问题标题】:Python Bar Chart not Displaying Correctly (Matplotlib)Python 条形图显示不正确(Matplotlib)
【发布时间】: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


    【解决方案1】:

    遍历您的数据并每次调用 bar() 是有意义的。 我尚未对此进行测试,但应该足以开始使用。

    y_pos_1 = y_pos_2 = 0
    for k, v in enumerate(data):
      abs_bottom = [y_pos_1, y_pos_2]
      plt.bar(x, v, bottom=abs_bottom, label=keys[k])
      y_pos_1 += v[0]
      y_pos_2 += v[1]
    

    基本上只保留每个条形底部的滚动计数。使用 enumerate() 获取索引,以便我们可以使用它来获取标签。

    【讨论】:

      猜你喜欢
      • 2019-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-05
      • 1970-01-01
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      相关资源
      最近更新 更多