首页 > 解决方案 > 带数字的堆叠条图

问题描述

我正在尝试使用 matplotlib 用堆栈栏绘制一些数据。

我写了一个代码,它没有数字就可以完美运行;

import numpy as np
import matplotlib.pyplot as plt

N = 5
menMeans = [20, 35, 30, 35, 27]
womenMeans = [25, 32, 34, 20, 25]
ind = np.arange(N)
width = 0.35

p1 = plt.bar(ind, menMeans, width, color='#d62728')
p2 = plt.bar(ind, womenMeans, width, bottom=menMeans)

plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))

plt.show()

这就是图表的图片

在此处输入图像描述

但我想在它们中间显示每个条的数字,如下所示:

在此处输入图像描述

我试图像这样编辑我的代码;

import numpy as np
import matplotlib.pyplot as plt

N = 5
menMeans = [20, 35, 30, 35, 27]
womenMeans = [25, 32, 34, 20, 25]
ind = np.arange(N)
width = 0.35

p1 = plt.bar(ind, menMeans, width, color='#d62728')
p2 = plt.bar(ind, womenMeans, width, bottom=menMeans)

plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))
for index, data in enumerate(menMeans):
    plt.text(x=index, y=data + 1, s=f"{data}", fontdict=dict(fontsize=20))
for index, data in enumerate(womenMeans):
    plt.text(x=index, y=data + 1, s=f"{data}", fontdict=dict(fontsize=20))
plt.show()

但它显示这样

在此处输入图像描述

我的错在哪里?你能修好它吗 ?

标签: pythonpython-3.xnumpymatplotlibplot

解决方案


您需要设置horizontalalignment='center'verticalalignment='center'然后使用正确的 y 偏移值。这是一种方法。您还可以使用简写形式hava

for index, data in enumerate(menMeans):
    plt.text(x=index, y=data/2, s=f"{data}", ha='center',
             va='center', fontsize=20)
    plt.text(x=index, y=data + (womenMeans[index]/2), s=f"{womenMeans[index]}", ha='center',
             va='center',fontsize=20)
plt.show()

在此处输入图像描述

编辑:回答您的第二个问题,添加以下行,这将为您提供下图

plt.text(x=index, y=data + womenMeans[index]+1, s=f"{data+womenMeans[index]}", 
         ha='center',fontsize=20)

在此处输入图像描述


推荐阅读