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

求助:制作按年份分组、展示各性别消费总额的堆叠条形图

解决按年份分组的性别消费堆叠条形图问题

原代码的核心问题

  • 未处理日期字段提取年份,也没按「年份+性别」分组,无法实现按年份对比各性别消费额的需求
  • groupby的计算结果未保存,后续代码完全没用到汇总后的真实数据
  • plt.bar(xp,genders)参数错误,条形图需要的是x轴位置和对应数值,这里传入性别字符串列表不符合要求
  • plt.xticks(xp,x)中的x变量未定义,注释的代码里bar1、male等变量也都未定义,逻辑不完整

修正后的完整代码

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

sns.set(style = "white", color_codes=True)
sales = pd.read_csv("/kaggle/input/mobile-sales-dataset/mobile_sales.csv")

# 1. 从日期字段提取年份(假设日期格式是MM-DD-YYYY)
sales['Year'] = pd.to_datetime(sales['Date'], format='%m-%d-%Y').dt.year

# 2. 按年份、性别分组,计算总消费额
gender_year_revenue = sales.groupby(['Year', 'CustomerGender'])['TotalRevenue'].sum().unstack()

# 3. 绘制堆叠条形图
ax = gender_year_revenue.plot(kind='bar', stacked=True, figsize=(10,6))

# 设置图表标签和标题
plt.ylabel('总消费金额')
plt.title('各年份不同性别总消费金额对比')
plt.xticks(rotation=0)  # 年份标签不旋转,更易读
plt.legend(title='性别')

# 显示图表
plt.show()

代码关键步骤说明

  • 日期处理:用pd.to_datetime解析日期,指定格式%m-%d-%Y确保解析正确,再提取年份字段
  • 分组汇总:用groupby(['Year', 'CustomerGender'])实现双维度分组,unstack()把性别转为列,方便直接绘制堆叠图
  • 堆叠图绘制:直接调用plot(kind='bar', stacked=True),pandas会自动处理x轴(年份)和各堆叠部分(性别)的数值,无需手动计算条形位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 08:30:12