简体   繁体   中英

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. 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 = [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] :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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