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

如何基于Pandas DataFrame绘制带百分比的LoanStatus占比饼图

问题描述

现有如下Pandas DataFrame:

df = pd.DataFrame([
    ['Fully Paid',1,1],
    ['Fully Paid',1,1],
    ['Fully Paid',1,0],
    ['Defaulted',1,0],
    ['Defaulted',1,0]
], columns=['LoanStatus', 'B', 'C'])

需要绘制饼图展示LoanStatus的占比(Fully Paid占60%,Defaulted占40%),已实现计数柱状图:

sns.countplot(x="LoanStatus",data=df)

但无法绘制符合预期的饼图,预期效果为:展示两种LoanStatus的数量及对应百分比的饼图。

解决方案

可以通过Matplotlib结合Pandas的统计函数实现需求,以下是两种实现方式:

方式1:仅显示百分比的饼图

先统计各LoanStatus的数量,再调用Matplotlib的pie()函数绘制:

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

# 创建DataFrame
df = pd.DataFrame([
    ['Fully Paid',1,1],
    ['Fully Paid',1,1],
    ['Fully Paid',1,0],
    ['Defaulted',1,0],
    ['Defaulted',1,0]
], columns=['LoanStatus', 'B', 'C'])

# 统计各状态的数量
status_counts = df['LoanStatus'].value_counts()

# 绘制饼图
plt.figure(figsize=(6, 6))  # 设置画布大小,保证饼图为圆形
plt.pie(
    status_counts.values,
    labels=status_counts.index,
    autopct='%1.1f%%',  # 格式化显示百分比(保留1位小数)
    textprops={'fontsize': 12},
    startangle=90  # 设置起始角度,优化视觉效果
)
plt.title('Loan Status 占比分布', fontsize=14)
plt.show()

方式2:同时显示数量和百分比的饼图

自定义百分比格式化函数,让饼图扇区同时展示占比和具体数量:

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

# 创建DataFrame
df = pd.DataFrame([
    ['Fully Paid',1,1],
    ['Fully Paid',1,1],
    ['Fully Paid',1,0],
    ['Defaulted',1,0],
    ['Defaulted',1,0]
], columns=['LoanStatus', 'B', 'C'])

# 统计各状态的数量
status_counts = df['LoanStatus'].value_counts()

# 自定义格式化函数:同时显示百分比和数量
def autopct_formatter(values):
    def format_func(pct):
        total = sum(values)
        count = int(round(pct * total / 100))
        return f'{pct:.1f}%\n({count}个)'
    return format_func

# 绘制饼图
plt.figure(figsize=(6, 6))
plt.pie(
    status_counts.values,
    labels=status_counts.index,
    autopct=autopct_formatter(status_counts.values),
    textprops={'fontsize': 12},
    startangle=90
)
plt.title('Loan Status 数量及占比分布', fontsize=14)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 21:45:35