在相对丰度条的顶部添加类别总值,Python

Add total values of categories on top of relative abundance bars, Python

我正在使用这样的相对丰度图:

但需要帮助才能在每个栏的顶部显示类别值的总量。结果应该是这样的:

又名。 x轴每个类别('1-2','2-3','3-4','4-5')的统计数量。

我的代码:

import pandas as pd
import matplotlib.pyplot as plt

data = {'Index A':[1,5,8,9],'Index B':[19,3,7,9],'Index C':[14,16,7,8]}
stacked_data = pd.DataFrame(data, index=['1-2','2-3','3-4','4-5'])

stacked_data = stacked_data.apply(lambda x: x*100/sum(x), axis=1)
list_of_colors = ['blue','red','yellow']
ax = stacked_data.plot(kind='bar', stacked=True, width=1, figsize=(9,8), edgecolor=None, color=list_of_colors)
    
plt.xlabel('Size', fontsize=15)
plt.ylabel('Relative abundance [%]', fontsize=15)
plt.xticks(fontsize=12, rotation=360)
plt.yticks(fontsize=12)
plt.legend(bbox_to_anchor=(1, .965), facecolor='white',loc=0, frameon=True, fontsize=12,title='Index')

plt.show()

感谢任何帮助!

在计算数据框的相对值之前获得总值。用这些总值的列表和图的 x-axis 的检索标签列表进行注释。注释的坐标基础是data-based.

import pandas as pd
import matplotlib.pyplot as plt

data = {'Index A':[1,5,8,9],'Index B':[19,3,7,9],'Index C':[14,16,7,8]}
stacked_data = pd.DataFrame(data, index=['1-2','2-3','3-4','4-5'])
total_data = stacked_data.sum(axis=1)
# print(total_data)
stacked_data = stacked_data.apply(lambda x: x*100/sum(x), axis=1)
list_of_colors = ['blue','red','yellow']
ax = stacked_data.plot(kind='bar', stacked=True, width=1, figsize=(9,8), edgecolor=None, color=list_of_colors)
    
plt.xlabel('Size', fontsize=15)
plt.ylabel('Relative abundance [%]', fontsize=15)
plt.xticks(fontsize=12, rotation=360)
plt.yticks(fontsize=12)
plt.legend(bbox_to_anchor=(1, .965), facecolor='white',loc=0, frameon=True, fontsize=12, title='Index')

# print(ax.get_xticklabels())
for i,(n,idx) in enumerate(zip(total_data,ax.get_xticklabels())):
    ax.text(x=idx.get_position()[0], y=100, s='n={}'.format(n), ha='center', fontdict={'size':18}, transform=ax.transData)
    
plt.show()