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

如何在ggplot中绘制时间序列不同时段的均值与置信区间?

用ggplot展示时间序列不同时段的均值及置信区间

步骤1:数据预处理与统计量计算

先把时间列转为可识别的时间格式,再按目标时段分组,计算每个时段的均值和置信区间(以下以95%置信区间为例,可按需调整置信水平)。

假设你的数据框为ts_data,包含datetime(时间列)和value(数值列):

# 加载依赖包
library(tidyverse)
library(lubridate)

# 模拟示例数据(已有数据可跳过)
set.seed(123)
ts_data <- tibble(
  datetime = seq(ymd_hms("2024-01-01 00:00:00"), ymd_hms("2024-01-10 23:00:00"), by = "hour"),
  value = rnorm(nrow(.), mean = 20, sd = 5) + 
    hour(datetime) * 0.3 + 
    sample(c(-2, 2), nrow(.), replace = TRUE)
)

# 按日期分组(可替换为hour/week/month,或自定义时段)
summary_data <- ts_data %>%
  mutate(date = date(datetime)) %>%
  group_by(date) %>%
  summarise(
    mean_val = mean(value, na.rm = TRUE),
    se = sd(value, na.rm = TRUE)/sqrt(n()),
    ci_low = mean_val - 1.96*se,
    ci_high = mean_val + 1.96*se
  ) %>%
  ungroup()

步骤2:用ggplot绘图

根据需求选择不同的可视化样式:

样式1:点+误差线

ggplot(summary_data, aes(x = date, y = mean_val)) +
  geom_errorbar(aes(ymin = ci_low, ymax = ci_high), width = 0.2, color = "#6366F1") +
  geom_point(color = "#1E40AF", size = 3) +
  labs(
    x = "日期",
    y = "均值",
    title = "每日均值及95%置信区间"
  ) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

样式2:填充置信区间带+均值线

若需要连续区间带效果,用geom_ribbon:

ggplot(summary_data, aes(x = date, y = mean_val)) +
  geom_ribbon(aes(ymin = ci_low, ymax = ci_high), fill = "#6366F1", alpha = 0.3) +
  geom_line(color = "#1E40AF", linewidth = 1) +
  geom_point(color = "#1E40AF", size = 2) +
  labs(
    x = "日期",
    y = "均值",
    title = "每日均值及95%置信区间"
  ) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

自定义时段分组处理

如果要按早中晚、工作日/周末这类自定义时段分组,用case_when创建分组列:

summary_data_custom <- ts_data %>%
  mutate(
    time_period = case_when(
      hour(datetime) %in% 6:11 ~ "上午",
      hour(datetime) %in% 12:17 ~ "下午",
      hour(datetime) %in% 18:23 | hour(datetime) %in% 0:5 ~ "夜间"
    ),
    date = date(datetime)
  ) %>%
  group_by(date, time_period) %>%
  summarise(
    mean_val = mean(value, na.rm = TRUE),
    se = sd(value, na.rm = TRUE)/sqrt(n()),
    ci_low = mean_val - 1.96*se,
    ci_high = mean_val + 1.96*se
  ) %>%
  ungroup()

# 分时段可视化
ggplot(summary_data_custom, aes(x = date, y = mean_val, color = time_period)) +
  geom_errorbar(aes(ymin = ci_low, ymax = ci_high), width = 0.2, position = position_dodge(0.5)) +
  geom_point(position = position_dodge(0.5), size = 2) +
  labs(
    x = "日期",
    y = "均值",
    title = "分时段均值及95%置信区间",
    color = "时段"
  ) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 02:06:16