Python 并排标注Matplotlib条的百分比

Python 并排标注Matplotlib条的百分比,python,matplotlib,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,

我已经创建了下图,但我想作为注释添加上面每个条的百分比,而不是数字。有人能帮我解决这个问题吗。注:我希望每三根杆组的百分比总和为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=[x.get_height()+y.get_height()+z.get_height()
对于zip中的x、y、z(rects1、rects2、rects3)]
然后在三个注释循环中,将
高度
文本除以
总计[i]

#“%s%”(高度)#旧
“%.1f%%%”(100*高/总计[i])#新

同时循环遍历每个组,然后您可以计算每个组的百分比:
对于枚举(zip(rects1、rects2、rects3))中的i(rect1、rect2、rect3)):