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

在R语言中绘制三轴图咨询:以value1为X轴,双Y轴为value2和value3

双Y轴图表实现方案

完全可以绘制以value1为X轴,value2(左Y轴)和value3(右Y轴)的双Y轴图表,下面提供两种R语言的常用实现方式:

方法一:基础R绘图

利用基础R的绘图函数直接构建双Y轴:

# 绘制左Y轴数据(value1 vs value2)
plot(df$value1, df$value2, pch = 16, col = "steelblue",
     xlab = "value1", ylab = "value2", main = "双Y轴对比图")

# 开启新图层,绘制右Y轴数据(value1 vs value3)
par(new = TRUE)
plot(df$value1, df$value3, pch = 17, col = "firebrick",
     xlab = "", ylab = "", axes = FALSE)
# 添加右侧Y轴
axis(side = 4, col = "firebrick", col.axis = "firebrick")
mtext("value3", side = 4, line = 3, col = "firebrick")

# 添加图例区分两组数据
legend("topright", legend = c("value2", "value3"),
       pch = c(16, 17), col = c("steelblue", "firebrick"))

方法二:ggplot2包实现

ggplot2通过sec_axis()创建辅助Y轴,建议对数据做线性缩放让刻度更协调:

library(ggplot2)

# 计算缩放比例(匹配两组数据的范围)
scale_ratio <- max(df$value2) / max(df$value3)

ggplot(df, aes(x = value1)) +
  # 左Y轴数据点
  geom_point(aes(y = value2), color = "steelblue", size = 3) +
  # 右Y轴数据点(应用缩放)
  geom_point(aes(y = value3 * scale_ratio), color = "firebrick", size = 3) +
  # 设置双Y轴
  scale_y_continuous(
    name = "value2",
    sec.axis = sec_axis(~ . / scale_ratio, name = "value3")
  ) +
  labs(x = "value1", title = "双Y轴对比图") +
  theme_minimal() +
  # 给轴标题上色区分
  theme(
    axis.title.y = element_text(color = "steelblue"),
    axis.title.y.right = element_text(color = "firebrick")
  )

注意:双Y轴图表可能存在视觉误导风险,仅在确实需要对比两组不同量级数据时使用,且需明确标注数据对应关系。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 14:55:05