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

如何用Seaborn绘制固定时段的时间序列数据(带均值曲线与误差带)

实现固定时段时间序列的均值与误差带可视化

当然可以实现这类可视化,下面是针对你提供的数据集的完整步骤:

步骤1:预处理数据,提取时段信息

首先需要从datetime列中拆分出时段标记和时间点(比如一天内的具体时间),这里以两种常见需求为例:

场景1:按6:00至次日6:00为一个周期

我们可以将datetime偏移6小时,让每个周期的起始点对齐到6:00,再提取日期作为周期标记,同时拆分出一天内的时间作为x轴的时间点:

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

# 生成示例数据
date_rng = pd.date_range(start="1.1.2023", end="10.1.2023", freq="15T")
df = pd.DataFrame(date_rng, columns=["datetime"])
df["value"] = pd.Series(range(len(date_rng)))

# 预处理:偏移6小时后提取周期日期,拆分一天内的时间
df["period"] = (df["datetime"] - pd.Timedelta(hours=6)).dt.date
df["time_of_day"] = df["datetime"].dt.time

场景2:按每8小时为一个周期

将一天划分为3个8小时时段,提取时段标签和对应的连续时间值(方便x轴连续显示):

# 预处理:按8小时划分时段
df["8h_period"] = pd.cut(df["datetime"].dt.hour,
                         bins=[0,8,16,24],
                         labels=["00:00-08:00", "08:00-16:00", "16:00-24:00"])
df["time_in_period"] = df["datetime"].dt.hour + df["datetime"].dt.minute/60  # 转换为小时数

步骤2:用Seaborn绘制均值曲线与误差带

使用seaborn.lineplot,通过指定参数计算均值并生成误差带,匹配你需要的效果:

针对场景1(6:00至次日6:00周期)的绘图代码

sns.set_theme(style="darkgrid")

# 将time_of_day转换为可排序的datetime格式
df["time_of_day"] = pd.to_datetime(df["time_of_day"], format="%H:%M:%S").dt.time

plt.figure(figsize=(12,6))
sns.lineplot(data=df, x="time_of_day", y="value", estimator="mean", ci="sd",
             linewidth=2, color="#007acc")

plt.title("6:00至次日6:00周期的value均值与标准差误差带")
plt.xlabel("一天内的时间")
plt.ylabel("value均值")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

针对场景2(每8小时周期)的绘图代码

plt.figure(figsize=(12,6))
sns.lineplot(data=df, x="time_in_period", y="value", hue="8h_period",
             estimator="mean", ci="sd", linewidth=2)

plt.title("每8小时周期的value均值与标准差误差带")
plt.xlabel("时段内的时间(小时)")
plt.ylabel("value均值")
plt.tight_layout()
plt.show()

关键参数说明

  • estimator='mean':指定对每个时间点的多周期数据计算均值
  • ci='sd':使用标准差作为误差带,也可替换为ci=95表示95%置信区间
  • 如果需要展示每个周期的原始曲线,可添加units='period'参数,同时保留均值曲线

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 12:05:21