如何在每个图中显示百分比?

问题描述 投票:0回答:1

当尝试绘制以下代码时,我得到了 4 张图表,但百分比仅显示在最后一张图表中。

fig, axes =plt.subplots(12,2,figsize=(12,50))
plt.subplots_adjust(wspace=0.9, hspace=0.9)
i=0
total = len(data['work_year']) 

for fea_name in fea:
     ax= axes[i//2, i%2]
     i += 1
     sns.countplot(x=fea_name, data=data, ax=ax,palette='icefire' )
     ax.set_title(f'Countplot of {fea_name}')

for i in range(len(fea), 12 * 2):
    fig.delaxes(axes[i//2, i%2])

for p in ax.patches:
        percentage = '{:.1f}%'.format(100 * p.get_height() / total)
        x = p.get_x() + p.get_width()/3
        y = p.get_y() + p.get_height()+50
        ax.annotate(percentage, (x, y))

plt.tight_layout()
plt.show()

仅在一张图表中显示百分比

plot seaborn subplot pyhook countplot
1个回答
0
投票
fig, axes =plt.subplots(12,2,figsize=(12,50))
plt.subplots_adjust(wspace=0.9, hspace=0.9)
i=0
total = len(data['work_year']) 

for fea_name in fea:
     ax= axes[i//2, i%2]
     i += 1
     sns.countplot(x=fea_name, data=data, ax=ax,palette='icefire' )
     ax.set_title(f'Countplot of {fea_name}')
    #  ax.tick_params(axis='x', rotation=45)

for i in range(len(fea), 12 * 2):
    fig.delaxes(axes[i//2, i%2])
for ax in axes.flat:
    for p in ax.patches:
        percentage = '{:.1f}%'.format(100 * p.get_height() / total)
        x = p.get_x() + p.get_width()/3
        y = p.get_y() + p.get_height()+50
        ax.annotate(percentage, (x, y))

plt.tight_layout()
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.