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

如何用ggplot2绘制指定刻度范围的双Y轴折线图?

问题描述

想用R的ggplot2绘制双Y轴折线图,要求:

  • 左侧Y轴(对应polity2数据)刻度范围固定为-10到10
  • 右侧Y轴(对应gee_totGDP数据)刻度范围固定为0到10
    当前代码生成的轴刻度不符合预期,左侧Y轴范围是-5到10,右侧是5到10,需要调整实现指定刻度。

原代码:

df %>% filter(Country == "Chile" & year >= 1973) %>% ggplot(aes(x = year)) +
geom_line(aes(y = polity2, colour = "Polity 2")) + geom_line(aes(y = gee_totGDP,colour = "gee_totGDP")) + scale_y_continuous(sec.axis = sec_axis(~.*-1,name = "gee_totGDP")) + scale_colour_manual(values = c("blue", "red"))

修正后的代码

df %>% 
  filter(Country == "Chile" & year >= 1973) %>% 
  ggplot(aes(x = year)) +
  # 绘制polity2,直接对应左轴
  geom_line(aes(y = polity2, colour = "Polity 2")) +
  # 将gee_totGDP转换为适配左轴-10到10范围的数值
  geom_line(aes(y = gee_totGDP * 2 - 10, colour = "gee_totGDP")) +
  # 固定左轴范围,同时设置右轴的逆转换刻度
  scale_y_continuous(
    limits = c(-10, 10),
    name = "Polity 2",
    sec.axis = sec_axis(
      trans = ~(. + 10)/2,  # 把左轴数值转回gee_totGDP的0-10范围
      name = "gee_totGDP"
    )
  ) +
  scale_colour_manual(values = c("blue", "red")) +
  theme_minimal() # 可选,优化图表样式

关键调整说明

  1. 固定左轴范围:通过limits = c(-10, 10)强制左侧Y轴显示-10到10的刻度,解决原代码左轴范围偏移的问题。
  2. 数据适配双轴:用gee_totGDP * 2 - 10将gee_totGDP的0-10范围映射到左轴的-10到10区间,确保两条折线的位置能匹配双轴刻度。
  3. 右轴逆转换:右侧轴通过~(. + 10)/2做逆运算,把左轴的数值转换回gee_totGDP的0-10刻度,保证右侧轴显示预期范围。

如果你的gee_totGDP原始数据范围不是0-10,可根据实际范围调整转换公式:假设原始范围是min_g到max_g,转换公式为y_left = (gee_totGDP - min_g) * 20/(max_g - min_g) - 10,右轴逆转换为y_right = (. + 10)*(max_g - min_g)/20 + min_g。

内容的提问来源于stack exchange,提问作者Pedro Ignacio Rosas Medina

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 19:00:53