如何在DataFrame中计算日/月聚合均值并使用ggplot单独绘图?
计算日/月均值并可视化的实现方案
下面是用Python的pandas和matplotlib/seaborn实现日/月均值计算及可视化的具体方案:
1. 导入依赖库
先导入所需工具库:
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # 若使用Jupyter Notebook,添加该行让图表直接显示 %matplotlib inline
2. 数据预处理
先处理数据中的缺失值(根据需求选择删除或填充,这里以删除x1/x2为空的行为例):
# 假设你的数据集存储在名为df的DataFrame中 df = df.dropna(subset=['x1', 'x2'])
3. 计算日均值
利用已有month和day列分组,计算x1、x2的日平均值:
# 分组计算日均值并重置索引 daily_mean = df.groupby(['month', 'day'])[['x1', 'x2']].mean().reset_index() # 生成便于可视化的日期标签(如"1-1"代表1月1日) daily_mean['date_label'] = daily_mean.apply(lambda row: f"{row['month']}-{row['day']}", axis=1)
4. 计算月聚合均值
按month分组,计算x1、x2的月平均值:
monthly_mean = df.groupby('month')[['x1', 'x2']].mean().reset_index()
5. 日均值可视化
用双折线图展示x1、x2的日均值变化趋势:
plt.figure(figsize=(16, 6)) sns.lineplot(data=daily_mean, x='date_label', y='x1', label='x1日均值') sns.lineplot(data=daily_mean, x='date_label', y='x2', label='x2日均值') plt.title('x1、x2日均值变化趋势') plt.xlabel('日期(月-日)') plt.ylabel('均值') plt.xticks(rotation=45) # 旋转x轴标签避免重叠 plt.legend() plt.tight_layout() plt.show()
6. 月均值可视化
用分组柱状图对比x1、x2的月均值:
plt.figure(figsize=(10, 6)) bar_width = 0.35 x = range(len(monthly_mean)) # 绘制两组柱状图 plt.bar([i - bar_width/2 for i in x], monthly_mean['x1'], width=bar_width, label='x1月均值') plt.bar([i + bar_width/2 for i in x], monthly_mean['x2'], width=bar_width, label='x2月均值') plt.title('x1、x2月均值对比') plt.xlabel('月份') plt.ylabel('均值') plt.xticks(x, monthly_mean['month']) plt.legend() plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者Dome
相关产品推荐
相关产品推荐

