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

如何用Matplotlib绘制含性别、细分、金额列的DataFrame饼图并显示百分比

解决Matplotlib饼图同时显示性别和客户细分标签的问题

我来帮你搞定这个饼图需求!你想要用total_amount作为饼图的数值数据,同时把gender和segment合并作为每个饼块的标签,还要显示百分比,对吧?先看看你原来代码里的几个小问题:

  • 你写的x="claim_amount"是笔误,应该是total_amount
  • plt.legend(d3.gender)里的d3是错误的,应该引用你的DataFramedf,不过其实我们可以把组合标签直接显示在饼图上,这样信息会更直观。

下面是完整的实现代码,我会一步步解释:

import matplotlib.pyplot as plt
import pandas as pd

# 你的原始数据
df = pd.DataFrame({
    'gender': {0: 'Female', 1: 'Female', 2: 'Female', 3: 'Male', 4: 'Male', 5: 'Male'},
    'Segment': {0: 'Gold', 1: 'Platinum', 2: 'Silver', 3: 'Gold', 4: 'Platinum', 5: 'Silver'},
    'total_amount': {0: 2110045.0, 1: 2369722.0, 2: 1897545.0, 3: 2655970.0, 4: 2096445.0, 5: 2347134.0}
})

# 1. 组合性别和客户细分作为饼块标签
df['combined_label'] = df['gender'] + ' - ' + df['Segment']

# 2. 绘制饼图
plt.figure(figsize=(8, 8))  # 设置画布大小,避免标签拥挤
wedges, texts, autotexts = plt.pie(
    x=df['total_amount'],  # 饼图的数值来源
    labels=df['combined_label'],  # 合并后的清晰标签
    autopct='%1.1f%%',  # 自动显示百分比,保留一位小数
    startangle=90,  # 旋转饼图起始角度,让布局更舒服
    wedgeprops={'linewidth': 1, 'edgecolor': 'white'}  # 给饼块加白色边框,区分更明显
)

# 3. 调整文本样式,提升可读性
plt.setp(autotexts, size=10, weight='bold')
plt.setp(texts, size=11)

# 添加标题
plt.title('Total Amount by Gender and Customer Segment', fontsize=12)

# 确保饼图是正圆形
plt.axis('equal')

plt.show()

代码说明:

  • 组合标签:通过字符串拼接把gender和Segment合并成类似Female - Gold的标签,每个饼块的含义一目了然。
  • 百分比显示:autopct='%1.1f%%'会自动计算每个饼块的占比并显示,如果你需要更多小数位,改成%1.2f%%即可。
  • 布局优化:设置画布大小、起始角度、饼块边框,这些细节能让饼图更美观易读;plt.axis('equal')可以避免饼图因画布比例变成椭圆形。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:05:07