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

ggplot2双X轴同量程下实现第二条轴左偏移8mm不对齐的问题

解决方案

完整可运行代码

library(ggplot2)
library(cowplot)
library(grid)

set.seed(123) # 固定随机数方便结果复现
data <- data.frame(temp_c=runif(100, min=-5, max=30), outcome=runif(100))

# 主图,固定X轴范围保证量程统一
plot <- ggplot(data) + 
  geom_point(aes(x=temp_c, y=outcome)) + 
  theme_classic() + 
  scale_x_continuous(limits = c(-5, 30)) + 
  labs(x='Temperature (Celsius)')

# 次X轴底图,实现摄氏转华氏的轴转换,同样固定X轴范围
x2plot <- ggplot(data) + 
  geom_point(aes(x=temp_c, y=outcome)) + 
  theme_classic() + 
  scale_x_continuous(
    limits = c(-5, 30), 
    label=function(x) round(x*9/5 + 32, 1)
  ) + 
  labs(x='Temperature (Fahrenheit)')

# 提取次轴和次轴标签组件
x_axis_grob <- get_x_axis(x2plot)
x_lab_grob <- get_plot_component(x2plot, "xlab-b")

# 给次轴、次轴标签添加向左8mm的偏移
offset_x_axis <- ggdraw() + 
  draw_grob(x_axis_grob, x = unit(-8, "mm"), width = unit(1, "npc"))
offset_x_lab <- ggdraw() + 
  draw_grob(x_lab_grob, x = unit(-8, "mm"), width = unit(1, "npc"))

# 拼接最终绘图
plot_grid(plot, offset_x_axis, offset_x_lab, align='v', axis='rl', ncol=1, 
          rel_heights=c(0.8, 0.05, 0.05))

核心修改说明

  • 给两个绘图对象都添加scale_x_continuous(limits = c(-5, 30)),强制固定X轴量程完全一致,避免数据波动导致的轴范围错位
  • 修正次轴的标签转换逻辑,实现了摄氏到华氏的正确换算,同时修正了原代码中Fahrenheit的拼写错误
  • 使用draw_grob()对提取出的次轴、次轴标签grob对象设置水平偏移,x = unit(-8, "mm")即表示向左偏移8mm,如需调整偏移量可直接修改该参数,负值向左偏移,正值向右偏移

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 22:27:04