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

ggplot2双x轴分别设置0-6与0-21限值的实现方法

要实现两个x轴起止位置对齐,需要利用ggplot2次坐标轴的线性映射特性调整,具体修改方案如下:


核心逻辑

ggplot2的次坐标轴无法独立设置取值范围,是主坐标轴的线性映射。你需要先将个体数(Ind)的取值缩放到与主坐标轴(样本数Sit,0-6)一致的区间,再通过次轴的转换公式还原显示为0-21的个体数刻度。

完整修改后代码

Input <- ("Sp1  Sp2 Sp3 Sp4 Sp5 Sp6
3   1   0   0   0   0
3   0   1   0   0   0
1   0   1   1   1   0
1   1   1   0   0   1
1   1   1   0   0   0
0   0   1   0   1   0")
comun <- read.table(textConnection(Input), header = TRUE)

library(vegan)
acumula <- specaccum(comun, method = "rarefaction")

plot_data <- data.frame("Sit" = c(0, acumula$sites),
                        "Ind" = c(0, acumula$individuals),
                        "Ric" = c(0, acumula$richness),
                        "lower" = c(0, acumula$richness - acumula$sd),
                        "upper" = c(0, acumula$richness + acumula$sd))
# 新增:将个体数缩放到主坐标轴0-6的区间
plot_data$Ind_scaled <- plot_data$Ind * 6 / 21

library(ggplot2)
ggplot(plot_data) +
  geom_line(aes(x = Sit, y = Ric),
            color = "blue", lwd = 2) +
  # 替换为缩放后的个体数
  geom_line(aes(x = Ind_scaled, y = Ric),
            color = "red", lwd = 2, lty = 2) +
  geom_ribbon(aes(x = Sit, y = Ric,
                  ymin = lower, ymax = upper), 
              linetype = 2, alpha = 0.3, fill = "yellow") +
  # 替换为缩放后的个体数
  geom_ribbon(aes(x = Ind_scaled, y = Ric,
                  ymin = lower, ymax = upper), 
              linetype = 2, alpha = 0.3, fill = "yellow") +
  scale_x_continuous("Samples", 
                     # 次轴通过线性转换还原为原始个体数刻度,0-6对应0-21
                     sec.axis = sec_axis(~ . * 3.5, 
                                         name = "Individuals"), 
                     # 主坐标轴限值设为0-6
                     limits = c(0, 6)) +
  ylab("Accumulated Richness")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:06:01