【问题标题】:Add labels as percentages instead of counts on a grouped bar graph in seaborn在 seaborn 的分组条形图上添加标签作为百分比而不是计数
【发布时间】:2022-01-16 08:33:15
【问题描述】:

我有一个分类数据集,我正在使用 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) 

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

【问题讨论】:

    标签: python pandas matplotlib seaborn bar-chart


    【解决方案1】:

    使用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 (%) 列和label the bars using ax.bar_label(通过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。

    【讨论】:

      猜你喜欢
      • 2021-09-12
      • 2016-04-21
      • 2022-09-25
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 2023-01-04
      • 1970-01-01
      相关资源
      最近更新 更多