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

ggplot中实现双层x轴标签(上层月份下层年份)的方法咨询

ggplot双层X轴标签实现方案

首先修正原代码的两处基础错误:

  • 日期向量的元素未加引号,会被识别为数值减法运算而非日期值
  • 最后一个日期存在笔误,2020-1-28需修正为2020-12-28,否则会生成异常的早期日期

方案1:单刻度双行标签(完全匹配需求,无需额外安装包)

该方案直接在日期标签中插入换行符,实现每个刻度下第一行显示月份、第二行显示对应年份,天然对齐:

# 加载所需基础包
library(ggplot2)
library(lubridate)

# 构造修正后数据集
Date <- c("2020-09-07","2020-09-14","2020-09-21","2020-09-28",
          "2020-10-07","2020-10-14","2020-10-21","2020-10-28",
          "2020-11-07","2020-11-14","2020-11-21","2020-12-28")
A <- c(28.2,28.4,28.6,28.8,28,28.5,27.6,27.9,27.9,28.1,28.4,29)
test <- data.frame(Date = as.Date(Date), A)

# 绘图代码
ggplot(test, aes(x=Date, y=A))+
  geom_line(na.rm=TRUE)+
  xlab("") + ylab("A")+
  scale_x_date(
    breaks = date_breaks("1 month"),
    # 标签第一行为月份缩写,第二行为年份
    labels = ~paste0(format(.x, "%b"), "\n", format(.x, "%Y"))
  )+
  scale_y_continuous(expand = c(0, 0), limits = c(26, 31))+
  theme_bw() +
  # 调整x轴文本垂直对齐,避免偏移
  theme(axis.text.x = element_text(vjust = 0.5))

方案2:同年份标签合并显示(适合跨多年数据场景)

如果需要将连续相同年份的标签合并为一个总标签,位于对应月份下方居中位置,可使用ggh4x扩展包的嵌套轴功能:

# 需先安装:install.packages("ggh4x")
library(ggh4x)

ggplot(test, aes(x=Date, y=A))+
  geom_line(na.rm=TRUE)+
  xlab("") + ylab("A")+
  scale_x_date(
    breaks = date_breaks("1 month"),
    labels = ~format(.x, "%b"),
    # 启用嵌套轴
    guide = guide_axis_nested(delim = "~")
  )+
  # 为日期添加上层年份分组
  facetted_pos_scales(
    x = list(scale_x_date(
      limits = range(test$Date),
      breaks = as.Date("2020-11-01"), # 年份标签居中位置
      labels = "2020",
      position = "bottom"
    ))
  )+
  scale_y_continuous(expand = c(0, 0), limits = c(26, 31))+
  theme_bw()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 23:09:04