简体   繁体   English

百分比注释 Matplotlib 条并排

[英]Percentage Annotation Matplotlib Bars side-by-side

I have created the following figure, but I want as annotation to add the percentage for each bar above, not the numbers.我创建了下图,但我想作为注释添加上面每个条的百分比,而不是数字。 Can someone help how to do this in this case of three bars side-by-side.在这种并排的三个酒吧的情况下,有人可以帮助如何做到这一点。 Note: I want the sum of the percentages to be 100% per group of three bars.注意:我希望每组三个条形的百分比总和为 100%。 I know only how to do this only for each category...我只知道如何为每个类别执行此操作...

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)

在此处输入图像描述

You could make a list of totals which gives you the total within each group:您可以制作一个totals列表,为您提供每个组内的总计:

totals = [x.get_height() + y.get_height() + z.get_height()
          for x, y, z in zip(rects1, rects2, rects3)]

And then in the three annotation loops, divide the height text by totals[i] :然后在三个注释循环中,将height文本除以totals[i]

# '%s' % (height) # old
'%.1f%%' % (100 * height / totals[i]) # new

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM