You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Seaborn或Matplotlib将countplot()的数值改为百分比?

实现Seaborn Countplot显示百分比的简便方法

当然有!不管用Seaborn还是Matplotlib,都有挺直观的方案来把countplot的数值展示改成百分比,我给你分享几种常用的实现方式:

方法一:Seaborn + 自定义百分比标注函数

这是最常用的方式,先画基础的countplot,再通过自定义函数给每个柱子添加上百分比标签:

普通单类别场景

import seaborn as sns
import matplotlib.pyplot as plt

# 加载示例数据(你可以替换成自己的数据集)
tips = sns.load_dataset("tips")

# 绘制基础countplot
ax = sns.countplot(x="day", data=tips)

# 定义添加百分比标注的函数
def add_percentage_labels(ax, total):
    for patch in ax.patches:
        height = patch.get_height()
        percentage = f'{100 * height / total:.1f}%'
        # 计算标注的位置(柱子中心上方)
        x_pos = patch.get_x() + patch.get_width() / 2
        y_pos = height
        ax.annotate(percentage, (x_pos, y_pos), ha='center', va='bottom', fontsize=10)

# 传入数据集总数调用函数
add_percentage_labels(ax, total=len(tips))
plt.ylabel('Count')
plt.show()

分组(带hue参数)场景

如果你的countplot是按hue分组的,只需要稍微调整函数,让百分比基于每组的总数计算:

ax = sns.countplot(x="day", hue="sex", data=tips)

def add_grouped_percentage_labels(ax):
    # 遍历每个柱子,计算所在组的总数
    for patch in ax.patches:
        height = patch.get_height()
        # 获取当前柱子所属组的所有柱子,求和得到组总数
        group_patches = [p for p in ax.patches if p.get_x() == patch.get_x()]
        group_total = sum(p.get_height() for p in group_patches)
        percentage = f'{100 * height / group_total:.1f}%'
        x_pos = patch.get_x() + patch.get_width() / 2
        y_pos = height
        ax.annotate(percentage, (x_pos, y_pos), ha='center', va='bottom', fontsize=10)

add_grouped_percentage_labels(ax)
plt.show()

方法二:直接用Matplotlib绘制百分比柱状图

如果你不需要Seaborn的样式,也可以先通过Pandas统计百分比,再用Matplotlib直接绘制:

import pandas as pd
import matplotlib.pyplot as plt

# 统计每个类别的百分比(normalize=True返回比例,乘以100转成百分比)
category_percentages = tips['day'].value_counts(normalize=True) * 100

# 绘制百分比柱状图
plt.bar(category_percentages.index, category_percentages.values)
plt.xlabel('Day')
plt.ylabel('Percentage (%)')

# 添加百分比标注
for idx, val in enumerate(category_percentages.values):
    plt.text(idx, val + 0.3, f'{val:.1f}%', ha='center')

plt.show()

额外小技巧:把y轴刻度改成百分比

如果想让y轴直接显示百分比刻度,而不是原始计数,可以用Matplotlib的PercentFormatter:

from matplotlib.ticker import PercentFormatter

ax = sns.countplot(x="day", data=tips)
# xmax传入数据集的总数,让刻度自动转换成百分比
ax.yaxis.set_major_formatter(PercentFormatter(xmax=len(tips)))
# 再配合之前的标注函数,效果更完整
add_percentage_labels(ax, total=len(tips))
plt.show()

这些方法都很灵活,你可以根据自己的数据集和需求来选择~

内容的提问来源于stack exchange,提问作者Liky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:46:08