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

如何使用ggplot仅按月份绘制日期数据(去除年份信息)

解决方案:跨年月度温度数据对比绘图

要实现不同年份的月度数据对比,核心是将不同年份的同月同日数据对齐到同一X轴位置,同时用年份区分数据点。以下是具体实现步骤:

1. 准备数据(加载依赖包+处理日期变量)

首先加载ggplot2和lubridate包,然后从原始日期中提取月-日和年份信息,将月-日转换为统一年份的日期(比如用2020年,确保包含2月29日),这样X轴就能按自然日期顺序排列:

library(ggplot2)
library(lubridate)

# 你的原始数据
df <- structure(list(date = structure(c(1592611200, 1624665600, 1626480000, 
1620086400, 1624147200, 1624752000, 1626566400, 1.566e+09, 1621036800, 
1651536000), tzone = "UTC", class = c("POSIXct", "POSIXt")), 
    location = c("POTOMAC RIVER", "POTOMAC RIVER", "POTOMAC RIVER", 
    "POTOMAC RIVER", "POTOMAC RIVER", "POTOMAC RIVER", "POTOMAC RIVER", 
    "POTOMAC RIVER", "POTOMAC RIVER", "POTOMAC RIVER"), avg_temp = c(70.875, 
    83.075, 92.025, 82.6, 87.8, 87.45, 82.15, 89.6, 75.125, 67.85
    )), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"
))

# 处理日期:提取月-日、年份,生成统一年份的日期变量
df$year <- year(df$date)
df$month_day_str <- format(df$date, "%m-%d")
df$month_day_date <- as.Date(paste0("2020-", df$month_day_str))

2. 修改ggplot代码实现对比

将X轴设为统一年份的月-日日期,用年份作为颜色区分,同时设置X轴刻度为月份+日期格式:

ggplot(df, aes(x = month_day_date, y = avg_temp, color = factor(year))) +
  geom_point(size = 3) + # 放大点便于观察
  scale_x_date(
    date_labels = "%b-%d", # 显示格式:月份缩写+日期(比如Jun-20)
    date_breaks = "1 month" # 每月一个刻度
  ) +
  ylab("Average Temperature (F)") + # 修正原代码的笔误(Weigh in Time应为Temperature)
  xlab("Month-Day") +
  labs(color = "Year") + # 图例标题改为年份
  theme_minimal()

效果说明

  • X轴仅显示月份和日期,不同年份的同一日期数据会对齐到同一位置
  • 通过颜色区分不同年份的温度数据,直观对比跨年度的温度变化
  • 若需要更精细的刻度(比如每周),可将date_breaks改为"1 week"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 12:56:11