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

ggplot2双坐标轴设置及误差棒范围适配方法

修正方案

核心是统一双Y轴的映射逻辑,取消硬编码的偏移量,直接对齐两个轴的边界值,调整后代码如下:

library(tidyverse)
library(ggplot2)

deciles <- data.frame(count = 1:10,
                  coef_maroon = c(0.005, 0.015, 0.015, 0.02, 0.03, 0.07, 0.09, 0.12, 0.12, 0.13),
                  ci_upper_maroon = c(0.008, 0.02, 0.025, 0.03, 0.04, 0.09, 0.11, 0.14, 0.13, 0.15),
                  ci_lower_maroon = c(0.001, 0.01, 0.005, 0, 0.01, 0.05, 0.07, 0.11, 0.11, 0.12),
                  coef_navy= c(0, -200, -400, -600, -800, -700, -900, -900, -1100, -1700),
                  ci_upper_navy = c(100, -100, -300, -500, -700, -600, -800, -700, -900, -1600),
                  ci_lower_navy = c(-100, -500, -700, -900, -850, -800, -950, -1000, -1200, -1900))

# 定义双轴映射规则:左轴[-2000, 0] 对应右轴[0, 0.15]
scl <- 2000 / 0.15
# 右轴值转左轴坐标公式:y_right * scl - 2000

ggplot(deciles) + 
  geom_point(aes(x = count, y = coef_navy, color = 'navy')) + 
  geom_point(aes(x = count, y = coef_maroon * scl - 2000, color = 'maroon')) +
  geom_errorbar(aes(x = count, ymin = ci_lower_navy, ymax = ci_upper_navy, color = 'navy'), width = 0) +     
  geom_errorbar(aes(x = count, ymin = ci_lower_maroon * scl - 2000, ymax = ci_upper_maroon * scl - 2000, color = 'maroon'), width = 0) +   
  labs(x = "Group", y = "") +
  scale_color_manual(values = c('maroon' = 'maroon', 'navy' = 'navy')) + 
  scale_y_continuous(
    limits = c(-2000, 0),
    expand = c(0.01, 0), # 仅保留极小边距避免元素贴边,消除多余空白
    sec.axis = sec_axis(~(. + 2000)/scl, name = "2nd axis")
  )

关键调整说明

  • 固定了左右轴的对应关系:左轴顶部0对应右轴顶部0.15,左轴底部-2000对应右轴底部0,完全匹配左轴下行趋势从左上角起始、右轴上行趋势从左下角起始的需求
  • 栗色系列的散点、误差棒上下限全部使用统一的转换公式,不会出现缩放错位问题
  • 手动固定左轴范围并关闭自动扩展边距,消除了顶部多余空白
  • 修正了geom_errorbar中width参数的位置,避免映射错误警告
  • 补充了颜色映射的键值对,避免版本差异导致颜色不匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:15:03