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

如何按天分组将速度数据在同图0-24小时轴绘制并分析趋势?

解决多天速度数据重叠绘图与日均速度计算问题

一、数据预处理:提取日内时间维度

首先确保你的DataFrame索引是datetime类型(如果尚未转换,先执行转换),然后提取每条数据的日内时间作为X轴基准:

# 确保索引为datetime类型
df.index = pd.to_datetime(df.index)

# 提取小时数作为X轴标识(也可提取时分秒:df['time'] = df.index.strftime('%H:%M:%S'))
df['hour'] = df.index.hour

二、同图重叠绘制多天数据

方法1:循环遍历单日数据叠加绘图

利用matplotlib的坐标轴对象,在同一画布上叠加绘制多天数据:

import matplotlib.pyplot as plt

# 创建画布与坐标轴
fig, ax = plt.subplots(figsize=(10,6))

# 定义需要对比的日期列表
target_dates = ['2023-07-07', '2023-07-08', '2023-07-09']

for date in target_dates:
    # 筛选当日数据
    daily_data = df.loc[date]
    # 以小时为X轴、速度为Y轴绘制,添加日期标签
    ax.plot(daily_data['hour'], daily_data['SPEED'], label=date)

# 配置图表样式
ax.set_xlabel('时间(小时)')
ax.set_ylabel('运行速度')
ax.set_xlim(0,24)  # 限定X轴范围为0-24小时
ax.legend(title='日期')
plt.title('多日运行速度小时级对比')
plt.show()

方法2:用Seaborn快速实现分组重叠绘图

通过hue参数按日期分组,更简洁地生成重叠折线图:

import seaborn as sns

# 添加日期列用于分组
df['date'] = df.index.date

# 绘制重叠折线图
plt.figure(figsize=(10,6))
sns.lineplot(data=df, x='hour', y='SPEED', hue='date')
plt.xlabel('时间(小时)')
plt.ylabel('运行速度')
plt.xlim(0,24)
plt.title('多日运行速度小时级对比')
plt.legend(title='日期')
plt.show()

三、计算日均速度与趋势分析

1. 计算日均速度

按日期分组,统计每天的平均运行速度:

# 按日期分组求速度均值
daily_avg_speed = df.groupby(df.index.date)['SPEED'].mean()

# 转换为DataFrame便于查看
daily_avg_speed_df = daily_avg_speed.reset_index()
daily_avg_speed_df.columns = ['日期', '日均速度']
print(daily_avg_speed_df)

2. 日均速度趋势可视化

绘制时序图观察日均速度的变化趋势:

plt.figure(figsize=(10,6))
daily_avg_speed.plot(kind='line', marker='o')
plt.xlabel('日期')
plt.ylabel('日均速度')
plt.title('日均运行速度趋势')
plt.grid(True)
plt.show()

问题根源说明

你之前多次调用plot()生成连续时序图,是因为DataFrame的索引是连续的datetime,每次绘图都会按时间顺序拼接数据。通过提取日内时间作为X轴基准,就能让多天数据在0-24小时的轴上实现重叠对比。

内容的提问来源于stack exchange,提问作者Van.d Bag

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 22:46:15