基于Pandas DataFrame绘制客户购买行为饼图的技术问询
问题描述
我想要基于记录客户购买行为的Pandas DataFrame绘制饼图,相关数据如下:
| PREMIUM_CUSTOMER | TOT_SALES |
|---|---|
| Mainstream | 750744.50 |
| Budget | 676211.55 |
| Premium | 507458.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()
关键修正点:
- 绘图方法调用错误:Pandas DataFrame的绘图方法是
plot.pie(),而非plt.pie(),正确路径为df_customer.plot.pie() - 参数传递错误:绘制饼图需通过
y参数指定数值列(TOT_SALES),无需将列名直接作为位置参数传入 - 标签优化:直接从DataFrame的
PREMIUM_CUSTOMER列读取标签,避免手动输入的误差 - 百分比格式修正:将
autopct='%1.11f%%'调整为%1.1f%%,保留1位小数即可保证可读性
内容的提问来源于stack exchange,提问作者coja56
相关产品推荐
相关产品推荐

