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

如何在R的ggplot geom_raster中设置Y轴年份刻度间隔或交错次Y轴

优化ggplot2 geom_raster图的Y轴年份显示方案

一、设置Y轴年份刻度为固定间隔(2年/5年)

原代码中将year转为因子类型,导致Y轴默认显示所有年份。要实现固定间隔的刻度,需先将year保持为数值型,再通过scale_y_continuous的breaks参数指定刻度断点:

year <- seq(1977,2021,1)
jan = runif(45, min=-4, max=4)
feb = runif(45, min=-4, max=4)
mar = runif(45, min=-4, max=4)
apr = runif(45, min=-4, max=4)
may = runif(45, min=-4, max=4)
jun = runif(45, min=-4, max=4)
jul = runif(45, min=-4, max=4)
aug = runif(45, min=-4, max=4)
sep = runif(45, min=-4, max=4)
oct = runif(45, min=-4, max=4)
nov = runif(45, min=-4, max=4)
dec = runif(45, min=-4, max=4)

df = data.frame(year,jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec)
df <- reshape2::melt(df, id.vars = "year")

# 保持year为数值型,无需转因子
df$variable <- factor(df$variable, levels = (unique(df$variable)))

library(ggplot2)
# 每2年一个刻度
e1 <- ggplot(df, aes(x = variable, y = year, fill = value)) +
  geom_raster()+
  guides(fill=guide_legend(title="Bohicon"))+
  scale_fill_gradientn(colours=c("#FF0000FF","#FFFFFFFF","#0000FFFF"))+
  theme(legend.position="bottom") +
  scale_y_continuous(breaks = seq(1977, 2021, 2),
                     limits = c(1977, 2021))

e1

# 每5年一个刻度,仅修改breaks参数
e2 <- ggplot(df, aes(x = variable, y = year, fill = value)) +
  geom_raster()+
  guides(fill=guide_legend(title="Bohicon"))+
  scale_fill_gradientn(colours=c("#FF0000FF","#FFFFFFFF","#0000FFFF"))+
  theme(legend.position="bottom") +
  scale_y_continuous(breaks = seq(1977, 2021, 5),
                     limits = c(1977, 2021))

e2

核心说明:

  • 移除df$year <- factor(...),数值型变量更便于控制刻度间隔
  • 用seq(start, end, interval)生成指定间隔的年份序列,作为breaks参数值

二、添加次Y轴实现刻度交错

通过次Y轴展示与主Y轴错开的年份,避免刻度密集重叠:

library(ggplot2)

# 主Y轴显示奇数年,次Y轴显示偶数年
e3 <- ggplot(df, aes(x = variable, y = year, fill = value)) +
  geom_raster()+
  guides(fill=guide_legend(title="Bohicon"))+
  scale_fill_gradientn(colours=c("#FF0000FF","#FFFFFFFF","#0000FFFF"))+
  theme(legend.position="bottom") +
  scale_y_continuous(
    breaks = seq(1977, 2021, 2), # 主轴:奇数年
    limits = c(1977, 2021),
    sec.axis = sec_axis(
      trans = ~., # 次轴与主轴数值完全对应
      breaks = seq(1978, 2020, 2), # 次轴:偶数年
      name = NULL # 隐藏次轴标题
    )
  ) +
  theme(
    # 调整次轴刻度边距,避免与主轴重叠
    axis.text.y.right = element_text(margin = margin(l = -10)),
    axis.ticks.y.right = element_line(margin = margin(l = -10))
  )

e3

核心说明:

  • sec.axis的trans = ~.确保次轴与主轴数值一致
  • 主轴和次轴分别设置错开的年份断点,通过theme调整次轴元素的边距,实现视觉上的交错效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 18:14:56