我刚刚开始使用matplotlib.pyplot并且有点卡住了。
使用matpltlib.pyplot文档中的示例,我使用以下代码创建了堆积条形图:
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()
但是我想在条形图上显示总数,我不知道如何。我见过this post,但遇到了问题:
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
,我会获得。
我想要的是这些数字直接位于第二个(蓝色)栏上方[就像我第一次尝试中2010栏上的524一样]。我错过了一些非常明显的东西吗?
与往常一样,任何帮助都将非常感谢! 干杯
答案 0 :(得分:6)
试试这个:
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')