如何在matplotlib中的水平条旁边显示百分比(文本)?

数据挖掘 Python matplotlib 海运
2021-10-05 03:02:51

我正在使用 seaborn 的计数图来显示 2 个分类数据的计数分布。很好,但我希望百分比显示在每个图的条形顶部。请问我该怎么做?

fig, ax = plt.subplots(1, 2)
sns.countplot(y = df['current_status'], ax=ax[0]).set_title('Current Occupation')
sns.countplot(df['gender'], ax=ax[1]).set_title('Gender distribution')

在此处输入图像描述

我已根据所做的评论进行了编辑,但我无法获得水平条右侧的百分比。这就是我所做的。

total = len(df['current_status'])*1.
ax = sns.countplot(y="current_status", data=df)
plt.title('Distribution of  Configurations')
plt.xlabel('Number of Axles')

for p in ax.patches:
        ax.annotate('{:.1f}%'.format(100*p.get_height()/total), (p.get_y()+0.1, p.get_height()+5))
_ = ax.set_xticklabels(map('{:.1f}%'.format, 100*ax.xaxis.get_majorticklocs()/total))

在此处输入图像描述

2个回答

这是一个在水平条右侧添加文本的工作示例:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

df = pd.DataFrame(np.array([['a'], ['a'], ['b']]), columns=['current_status'])
ax = sns.countplot(y="current_status", data=df)
plt.title('Distribution of  Configurations')
plt.xlabel('Number of Axles')

total = len(df['current_status'])
for p in ax.patches:
        percentage = '{:.1f}%'.format(100 * p.get_width()/total)
        x = p.get_x() + p.get_width() + 0.02
        y = p.get_y() + p.get_height()/2
        ax.annotate(percentage, (x, y))

plt.show()

输出:

x您可以通过更改和的公式来移动文本y例如,要将它们放在顶部:

x = p.get_x() + p.get_width() / 2
y = p.get_y() - 0.02

这是注释轴的一般准则。

# plot1 real 

fig, ax= plt.subplots(figsize =(12,40))
sns.set_style('whitegrid')
sns.set_context('notebook')
#sns.set(font_scale=2)
plt.fontsize =(35)

ax=sns.barplot( palette="Dark2",ax=ax,

            x='square km', y='state',data=d)
total=len(d['state'])
for p in ax.patches:
    percentage ='{:,.0f}KM²'.format(p.get_width())
    width, height =p.get_width(),p.get_height()
    x=p.get_x()+width+0.02
    y=p.get_y()+height/2
    ax.annotate(percentage,(x,y))

plt.xticks(rotation =50,fontsize =18)
plt.yticks(rotation =50,fontsize =20)

plt.title('NIGERIA\'S 36 STATES & FCT RANKED\n IN ORDER OF LAND SURFACE AREA (KM²)',
         fontsize =30 
         )
plt.xlabel ('SQUARE KM',fontsize =24)
plt.ylabel ('STATE',fontsize =24)

plt.show ()

在此处输入图像描述