在条形图中显示值

时间:2019-02-26 21:17:43

标签: python-3.x numpy matplotlib bar-chart

我生成了该图,并且无法正确显示每个条的值。这是我的条形图:

enter image description here

这是我创建上述情节的代码:

X_perc = [10, 7, 3, 5, 5]
cols = ['3.1-4.14', '4.14-5.18', '6.22-7.26', '7.26-8.3', '5.18-6.22']
data = np.array([[10, 7, 5, 5, 3],])

fig, ax=plt.subplots()
for i, (name, v) in enumerate(zip(cols, X_perc)):
    bottom=np.sum(data[:,0:i], axis=1)
    ax.bar(1,data[:,i], bottom=bottom, label="{}".format(name))
    ax.text(0.7, (v*i)/v * i + v + i, str(v), fontweight='bold')

plt.legend(framealpha=1)
plt.axis([-10, 10, 0, 31])
plt.tick_params(
    axis='x',          
    which='both',      
    bottom=False,      
    top=False,         
    labelbottom=False) 

1 个答案:

答案 0 :(得分:0)

您可以使用累积的位置总和来注释堆积的条形图

positions = np.cumsum(data)

fig, ax=plt.subplots()
for i, (name, v) in enumerate(zip(cols, X_perc)):
    bottom=np.sum(data[:,0:i], axis=1)
    ax.bar(1,data[:,i], bottom=bottom, label="{}".format(name))
    ax.text(0.7, positions[i], str(v), fontweight='bold') # Use it here

enter image description here