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

基于Pandas DataFrame绘制客户购买行为饼图的技术问询

问题描述

我想要基于记录客户购买行为的Pandas DataFrame绘制饼图,相关数据如下:

PREMIUM_CUSTOMERTOT_SALES
Mainstream750744.50
Budget676211.55
Premium507458.95

我目前编写的代码如下:

plt.style.use("fivethirtyeight")
labels = ['Mainstream','Budget','Premium']
df_customer.plt.pie("PREMIUM_CUSTOMER","TOT_SALES",labels=labels,wedgeprops={'edgecolor':'black'}, shadow = True,startangle =90, autopct='%1.11f%%')
plt.title("Percentage of sales to customer types ")
plt.tight_layout()
plt.show()

代码修正与说明

你的代码存在几处语法和参数使用错误,以下是修正后的完整代码:

import matplotlib.pyplot as plt
import pandas as pd

# 若已存在DataFrame可跳过此初始化步骤
data = {
    'PREMIUM_CUSTOMER': ['Mainstream', 'Budget', 'Premium'],
    'TOT_SALES': [750744.50, 676211.55, 507458.95]
}
df_customer = pd.DataFrame(data)

plt.style.use("fivethirtyeight")
# 调用DataFrame的plot.pie方法,指定数值列和标签列
df_customer.plot.pie(
    y='TOT_SALES',
    labels=df_customer['PREMIUM_CUSTOMER'],
    wedgeprops={'edgecolor':'black'},
    shadow=True,
    startangle=90,
    autopct='%1.1f%%'
)
plt.title("不同客户类型的销售额占比")
plt.ylabel('')  # 移除默认y轴标签,优化图表整洁度
plt.tight_layout()
plt.show()

关键修正点:

  1. 绘图方法调用错误:Pandas DataFrame的绘图方法是plot.pie(),而非plt.pie(),正确路径为df_customer.plot.pie()
  2. 参数传递错误:绘制饼图需通过y参数指定数值列(TOT_SALES),无需将列名直接作为位置参数传入
  3. 标签优化:直接从DataFrame的PREMIUM_CUSTOMER列读取标签,避免手动输入的误差
  4. 百分比格式修正:将autopct='%1.11f%%'调整为%1.1f%%,保留1位小数即可保证可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:05:22