在 seaborn 的分组条形图中将标签添加为百分比而不是计数

Add labels as percentages instead of counts on a grouped bar graph in seaborn

我有一个分类数据集,我正在使用 seaborn 绘制条形图。但是我无法在百分比值的条形顶部添加标签。数据集如下所示:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'Day': ['Mon', 'Tue', 'Wed', 'Thur', 'Fri',
                           'Mon', 'Tue', 'Wed', 'Thur', 'Fri'],
                   'Customers': [44, 46, 49, 59, 54,
                                 33, 46, 50, 49, 60],
                   'Time': ['M', 'M', 'M', 'M', 'M',
                            'E', 'E', 'E', 'E', 'E']})

#view DataFrame
df

这是绘制分组条形图的代码:

import matplotlib.pyplot as plt
import seaborn as sns

#set seaborn plotting aesthetics
sns.set(style='white')

#create grouped bar chart
sns.barplot(x='Day', y='Customers', hue='Time', data=df) 

现在我想在条形图顶部添加标签,但以百分比值表示。请帮忙

使用groupby.transform计算每天的拆分百分比:

df['Customers (%)'] = df.groupby('Day')['Customers'].transform(lambda x: x / x.sum() * 100)

#     Day  Customers Time  Customers (%)
# 0   Mon         44    M      57.142857
# 1   Tue         46    M      50.000000
# 2   Wed         49    M      49.494949
# 3  Thur         59    M      54.629630
# 4   Fri         54    M      47.368421
# 5   Mon         33    E      42.857143
# 6   Tue         46    E      50.000000
# 7   Wed         50    E      50.505051
# 8  Thur         49    E      45.370370
# 9   Fri         60    E      52.631579

然后绘制这个新的 Customers (%) 列和 (通过 fmt 参数设置百分比格式):

ax = sns.barplot(x='Day', y='Customers (%)', hue='Time', data=df) 

for container in ax.containers:
    ax.bar_label(container, fmt='%.0f%%')

注意 ax.bar_label 需要 matplotlib 3.4.0。