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

如何用ggplot2绘制以年为分组、月日为X轴的时序折线图

问题描述

我有一份逐小时测量数据集,已完成数据预处理:

histdata_shinyApp <- read_csv("RadData_Hourly_2005_2020.csv", 
                                   header=TRUE,
                                   skip= 8,
                                   dtoken = refreshable_token)%>%
  mutate(TIMESTAMP=as.POSIXct(time, format='%Y%m%d:%H%M'),
         date = ymd(as.Date(TIMESTAMP)),
         year = format(date, "%Y"),
         month = format(date, "%b"),
         day = format(date, "%d"),
         time= hms(format(as.POSIXct(TIMESTAMP, format='%Y-%m-%d %H:%M:%S'),format = "%H:%M:%S")),
         .before=1)%>%
  mutate(month=factor(month, 
                      levels=c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), 
                      labels=c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
                      ),
         Gb.i.=as.numeric(Gb.i.)
         )%>%
  pivot_longer(cols = Gb.i.:WS10m, 
               names_to = "variable")

我想用ggplot2绘制折线图,要求:

  • X轴为日期(按月份分面展示)
  • 每条折线对应一个年份
  • 展示均值及标准误(和ggpubr::ggline(x="day", y="value", add="mean_se", facet.by="month")效果一致)

之前尝试的ggplot2代码未达到预期:

library(ggplot2)
library(dplyr)
histdata_shinyApp%>%
  filter(., variable=="Gb.i.")%>%
  ggplot() +
  geom_line(aes(x=month, y=value, group=year, color = year))+
  geom_point(aes(x=month, y=value, group=year, color = year))

问题在于X轴显示逻辑错误,分组着色也不符合预期。

解决方案

要复刻ggpubr的效果,需先对数据做聚合处理,再用ggplot2绘制分面折线图:

  1. 数据聚合(计算均值和标准误)
library(ggplot2)
library(dplyr)

# 过滤目标变量,按月份、日期、年份聚合计算均值和标准误
plot_data <- histdata_shinyApp %>%
  filter(variable == "Gd.i.") %>% # 可替换为你需要的变量,如"Gb.i."
  group_by(month, day, year) %>%
  summarise(
    mean_value = mean(value, na.rm = TRUE),
    se_value = sd(value, na.rm = TRUE)/sqrt(n()),
    .groups = "drop"
  ) %>%
  mutate(day = as.integer(day)) # 将日期转为整数,保证X轴顺序正确
  1. 使用ggplot2绘制分面折线图
ggplot(plot_data, aes(x = day, y = mean_value, color = year, group = year)) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 1.5) +
  # 添加标准误误差线
  geom_errorbar(aes(ymin = mean_value - se_value, ymax = mean_value + se_value), 
                width = 0.5, alpha = 0.7) +
  # 按月份分面,保持预设的月份顺序
  facet_wrap(~month, scales = "free_x") +
  # 调整标签和主题样式
  labs(x = "日期", y = "均值", color = "年份") +
  theme_bw() +
  theme(
    strip.background = element_rect(fill = "#f0f0f0"),
    strip.text = element_text(face = "bold")
  )

关键修正点:

  • 替换原代码中错误的X轴变量,改用day作为X轴,通过facet_wrap(~month)实现按月份分面展示
  • 先对逐小时数据做聚合计算,匹配ggpubr的mean_se逻辑
  • 将day转为整数,避免X轴按字符乱序排列
  • 通过group = year和color = year确保每条折线对应单个年份

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 09:22:23