如何用Pandas绘制按客户类别分组的月均Volume时间序列折线图?
按客户类别分组的月度平均Volume时间序列折线图绘制方法
要实现按客户类别展示月度平均Volume的时间序列折线图,可按以下步骤操作:
1. 计算月度类别平均Volume
首先对原始数据按月份和客户类别分组,计算每个组的Volume平均值:
import pandas as pd # 加载样例数据 df = pd.DataFrame({'cust_id': [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3], 'month': [200101, 200102, 200103, 200104, 200101, 200102, 200103, 200104, 200101, 200102, 200103, 200104], 'volume': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 'category': [1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2]}) # 分组计算月度平均Volume monthly_avg = df.groupby(['month', 'category'])['volume'].mean().reset_index()
2. 转换月份为时间格式
原始数据中的月份是整数格式(如200101),需要转换为datetime类型,确保横轴按时间顺序正确显示:
monthly_avg['month'] = pd.to_datetime(monthly_avg['month'], format='%Y%m')
3. 绘制折线图
可以选择matplotlib手动绘制,或用seaborn快速生成美观的分组折线图:
方法一:使用Matplotlib
import matplotlib.pyplot as plt plt.figure(figsize=(10, 6)) # 分别绘制两个类别的折线 plt.plot(monthly_avg[monthly_avg['category'] == 1]['month'], monthly_avg[monthly_avg['category'] == 1]['volume'], marker='o', label='类别1') plt.plot(monthly_avg[monthly_avg['category'] == 2]['month'], monthly_avg[monthly_avg['category'] == 2]['volume'], marker='s', label='类别2') # 添加图表标签与样式 plt.xlabel('月份') plt.ylabel('月度平均Volume') plt.title('不同客户类别的月度平均Volume趋势') plt.legend() plt.grid(True, linestyle='--', alpha=0.7) # 自动调整日期标签,避免重叠 plt.gcf().autofmt_xdate() plt.show()
方法二:使用Seaborn(更简洁)
import seaborn as sns plt.figure(figsize=(10, 6)) # 直接传入分组数据,hue参数指定按category分组 sns.lineplot(data=monthly_avg, x='month', y='volume', hue='category', marker='o') plt.xlabel('月份') plt.ylabel('月度平均Volume') plt.title('不同客户类别的月度平均Volume趋势') plt.grid(True, linestyle='--', alpha=0.7) plt.gcf().autofmt_xdate() plt.show()
内容的提问来源于stack exchange,提问作者Nick
相关产品推荐
相关产品推荐

