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

如何在ggplot图表X轴添加每月10日的日期标签?

问题:在ggplot时间轴X轴添加每月10日标签

我正在制作如下图表,希望在X轴上添加每月10日的标签,同时保留图表其余元素,有没有简便方法?

原代码:

df1 <- read.table(text = "DT   odczyt.1 odczyt.2
'2023-01-18 00:00:00'   686 1.5
'2023-02-18 23:00:00'   487 6.8
'2023-03-04 00:00:00'   498 1.5
'2023-04-20 03:00:00'   961 1.54
'2023-06-21 05:00:00'   397 1.6
'2023-08-10 19:00:00'   532 6.6
'2023-08-21 23:00:00'   493 3.8
'2023-09-19 01:00:00'   441 9.2
'2023-11-3 07:00:00'    793 8.5
'2023-12-21 13:00:00'   395 5.5", header = TRUE) %>% 
  mutate (DT = as.POSIXct(DT))

ggplot (df1) +
  geom_line(aes (x = DT, y = odczyt.1), color = "indianred") +
  scale_x_datetime(breaks = "1 month",
                   minor_breaks = "2 day") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5),
        legend.position = "top",
        legend.justification = "center") 

解决方法

可以通过自定义scale_x_datetime的breaks参数,生成每月10日的时间点作为X轴标签,同时保留原图表的所有其他设置。

方法1:手动生成时间点

先根据数据的时间范围生成每月10日的POSIXct格式时间,再传入breaks:

# 生成每月10日的标签时间点
date_range <- range(df1$DT)
# 生成每个月的起始日期,再替换为当月10日
monthly_10th <- seq.Date(as.Date(date_range[1]), as.Date(date_range[2]), by = "month")
monthly_10th <- as.POSIXct(paste0(format(monthly_10th, "%Y-%m"), "-10 00:00:00"))

# 修改后的绘图代码
ggplot(df1) +
  geom_line(aes(x = DT, y = odczyt.1), color = "indianred") +
  scale_x_datetime(breaks = monthly_10th,
                   minor_breaks = "2 day") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5),
        legend.position = "top",
        legend.justification = "center")

方法2:自定义函数自动生成(更灵活)

直接在breaks参数中传入函数,根据X轴的自动范围生成每月10日的时间点,无需手动计算数据范围:

ggplot(df1) +
  geom_line(aes(x = DT, y = odczyt.1), color = "indianred") +
  scale_x_datetime(
    breaks = function(x) {
      # 基于X轴范围生成每个月10日的时间点
      seq.Date(as.Date(lubridate::floor_date(x[1], "month")), 
               as.Date(lubridate::ceiling_date(x[2], "month")), 
               by = "month") |>
        paste0("-10") |>
        as.POSIXct()
    },
    minor_breaks = "2 day"
  ) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5),
        legend.position = "top",
        legend.justification = "center")

两种方法都能保留原图表的minor_breaks、主题样式等所有元素,同时实现X轴标签显示每月10日的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:22:21