python - 带数字的堆叠条图
问题描述
我正在尝试使用 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()
但它显示这样
我的错在哪里?你能修好它吗 ?
解决方案
您需要设置horizontalalignment='center'
,verticalalignment='center'
然后使用正确的 y 偏移值。这是一种方法。您还可以使用简写形式ha
和va
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)
推荐阅读
- windows - Google Cloud SDK v274.0.0 更新要求在只有 Python 3+ (Windows) 的机器上使用 Python 2.7 解释器
- topic-modeling - 使用 Mallet 进行主题建模 - 主题键输出参数
- c# - asp.net core 3 MVC上的模型绑定属性为空
- java - 使用spring mvc验证具有特定列的整行
- sas - SAS- 如果 columnA 或 columnB 或 columnC 包含 '1' 那么 column1 ='1'
- azure-redis-cache - Azure Redis 缓存:没有可用于服务此操作的连接;现有连接被远程主机强行关闭
- xamarin.forms - 如何在 xamarin.forms.ios 的列表视图中隐藏输入键盘
- svn - 如何使用 svn ant 提交文件,包括已删除的文件
- angular - 为什么 Angular 6 不能识别具有多个参数的管道?
- java - Thymeleaf - 有没有办法在控制器中获取空值而不是空白字段的空白字符串?