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

如何在ggplot中为分类X轴添加双Y轴?附示例代码

解决方案:ggplot添加分类X轴双Y轴图表

首先修正你代码里的两处小问题:%>%符号缺失一个%,以及alpha=10(alpha取值范围是0-1,这里改为1)。下面是实现双Y轴的完整代码,同时保留按Type分组的样式:

library(ggplot2)
library(dplyr)

# 创建数据集
df <- data.frame(Sample=c(1,2,3,4,5,6,7,8,9),
                 Weight=c(53, 67, 89, 64, 84,77,55,78,99),
                 Height=c(167,198,177,167,199,178,165,190,188),
                 Type=factor(c("healthy","healthy","ill","healthy","ill","healthy","healthy","ill","healthy")))

# 计算缩放比例:将Height的数值范围映射到Weight的范围
weight_range <- range(df$Weight)
height_range <- range(df$Height)
scale_factor <- diff(weight_range) / diff(height_range)

# 绘制双Y轴图表
p <- df %>%
  ggplot(aes(x = Sample)) +
  # 左侧Y轴:Weight的点和平滑线
  geom_point(aes(y = Weight, color = Type), alpha = 1, size = 0.5) +
  geom_smooth(aes(y = Weight, color = Type, group = Type)) +
  # 右侧Y轴:Height的点(用三角形区分)和平滑线(用虚线区分)
  geom_point(aes(y = (Height - height_range[1])*scale_factor + weight_range[1], color = Type), 
             alpha = 1, size = 0.5, shape = 17) +
  geom_smooth(aes(y = (Height - height_range[1])*scale_factor + weight_range[1], color = Type, group = Type), 
              linetype = "dashed") +
  # 设置双Y轴:左侧显示Weight,右侧通过转换显示原始Height值
  scale_y_continuous(
    name = "Weight",
    sec.axis = sec_axis(
      trans = ~(. - weight_range[1])/scale_factor + height_range[1],
      name = "Height"
    )
  ) +
  # 调整X轴文本角度
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

p

关键说明:

  • 由于Weight和Height的数值范围差异大,必须通过缩放将Height值映射到Weight的范围内,才能在同一坐标系中显示。
  • 用不同的点形状(三角形)和线类型(虚线)区分两个指标的图层,避免混淆。
  • sec_axis的trans参数用于将缩放后的数值转换回原始Height值,确保右侧Y轴显示正确的刻度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 04:46:24