本文介绍了在条形图中显示堆叠条形上方的总数:matplotlib.pyplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用 matplotlib.pyplot 并且有点卡住了.

I am just starting out with matplotlib.pyplot and am a little stuck.

使用matpltlib.pyplot文档中的示例,我创建了一个堆积的条形图使用以下代码:

Using the example in the matpltlib.pyplot documentation, I have created a stacked bar chart using the following code:

import numpy as np
import matplotlib.pyplot as plt

N = 7
OECD = (242, 244, 255, 263, 269, 276, 285)
NonOECD = (282, 328, 375, 417, 460, 501, 535)
Sum = ('524', '572', '630', '680', '729', '777', '820')
ind = np.arange(N)
width = 0.5

p1 = plt.bar(ind, NonOECD, width, color = 'r')
p2 = plt.bar(ind, OECD, width, color = 'b', bottom = NonOECD)

plt.ylabel('Quadrillion Btu')
plt.title('World Total Energy Consumption 2010 - 2040')
plt.xticks(ind+width/2., ('2010', '2015', '2020', '2025', '2030', '2035', '2040'))
plt.yticks(np.arange(0, 1001, 200))
plt.legend((p1[0], p2[0]), ('Non - OECD', 'OECD'), loc = 2, frameon = 'false')
plt.tick_params(top = 'off', bottom = 'off', right = 'off')
plt.grid(axis = 'y', linestyle = '-')

plt.show()

但是我想在条形顶部显示总数,但我无法弄清楚如何.我见过 这篇文章但我遇到了问题:

However I want to display the totals on top of the bars and I cannot quite work out how. I have seen this post but am having issues:

for ii,rect in enumerate(p1):
    h1 = rect.get_height()
for ii,rect in enumerate(p2):
    h2 = rect.get_height()
    height =
    plt.text(rect.get_x()+rect.get_width()/2., height, '%s'% (Sum[ii]), ha = 'center', va='bottom')

如果我使用 height = h1 ,则会得到;如果我使用 height = h2 ,则会得到;如果我使用 height = h1 + h2 我得到 .

If I use height = h1 I get ; if I use height = h2 I get ; if I use height = h1 + h2 I get .

我想要的是这些数字直接位于第二个(蓝色)柱上方(例如我第一次尝试中2010年柱上的524).我是否遗漏了一些非常明显的东西?

What I want is these numbers sitting directly on above the second (blue) bar [like the 524 on the 2010 bar in my 1st attempt]. Am I missing something really obvious?

一如既往,任何帮助将不胜感激!干杯

As always, any help would be much appreciated!Cheers

推荐答案

尝试一下:

for r1,r2 in zip(p1,p2):
    h1 = r1.get_height()
    h2 = r2.get_height()
    plt.text(r1.get_x()+r1.get_width()/2., h1+h2, '%s'% (h1+h2), ha = 'center', va='bottom')

这篇关于在条形图中显示堆叠条形上方的总数:matplotlib.pyplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 04:03