python - 百分比注释 Matplotlib 条并排
问题描述
我创建了下图,但我想作为注释添加上面每个条的百分比,而不是数字。在这种并排的三个酒吧的情况下,有人可以帮助如何做到这一点。注意:我希望每组三个条形的百分比总和为 100%。我只知道如何为每个类别执行此操作...
fig = plt.figure(figsize=(15, 8));
ax5 = fig.add_subplot(1, 1, 1);
ax5.set_xticklabels(ff.index.tolist(), size=12)
# Custom Y axis-ticks
y_ticks = np.arange(0, 400, 50)
yrange = (y_ticks[0], y_ticks[-1])
ax5.set_ylim(yrange)
ax5.set_yticklabels(y_ticks, size = 12)
ax5.set_yticks(y_ticks)
# set the xlim
ax5.set_xlim(0, len(labels))
# get your locations
dim = np.arange(0.35,len(labels),1);
# set the locations of the xticks to be on the integers
ax5.set_xticks(dim)
# Custom X - label
ax5.set_xlabel('Mode of Information', size=16, fontweight='bold')
# Custom X - label
ax5.set_ylabel('Number of volunteers', size=16, fontweight='bold')
rects1 = ax5.bar(x + width, Rem, width, label='Remained the same', color='coral',
edgecolor='black')
rects2 = ax5.bar(x + (width*2), Inc, width, label='Increased', color='forestgreen',
edgecolor='black')
rects3 = ax5.bar(x + (width*3), Dec, width, label='Decreased', color='royalblue',
edgecolor='black')
for i,rect in enumerate(rects1): # for each bar
height = rect.get_height()
ax5.text(rect.get_x() + rect.get_width() / 2, rect.get_height() + 3, '%s'% (height),
ha='center', va='bottom', color = 'black', size = 12)
for i,rect in enumerate(rects2): # for each bar
height = rect.get_height()
ax5.text(rect.get_x() + rect.get_width() / 2, rect.get_height() + 3, '%s'% (height),
ha='center', va='bottom', color = 'black', size = 12)
for i,rect in enumerate(rects3): # for each bar
height = rect.get_height()
ax5.text(rect.get_x() + rect.get_width() / 2, rect.get_height() + 3, '%s'% (height),
ha='center', va='bottom', color = 'black', size = 12)
解决方案
您可以列出一个列表,totals
其中列出了每个组中的总数:
totals = [x.get_height() + y.get_height() + z.get_height()
for x, y, z in zip(rects1, rects2, rects3)]
然后在三个注释循环中,将height
文本除以totals[i]
:
# '%s' % (height) # old
'%.1f%%' % (100 * height / totals[i]) # new
推荐阅读
- gradle - WiX/SetupBuilder 在 vbscript 中获取 INSTALLDIR 的值
- python - 从函数中收集警告的最 Pythonic 方式
- javascript - 未捕获的类型错误:无法读取未定义的属性“控件”
- c++ - 如何将交错的图像复制到单独的缓冲区
- c# - 如何在机器人框架 V4 中使用 OAuthPrompt 禁用幻数
- java - Selenium:未知错误无法单击自定义下拉菜单,尽管它存在
- java - 如何读取多个方阵并处理矩阵并在控制台中打印
- java - Java中LinkedList的Naftalins大O分析
- elasticsearch - 是否可以将响应从 http_poller 拆分为 elasticsearch 中的多个文档
- python-3.x - 阅读 dicom repo 时出现编码问题