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
相关产品推荐
相关产品推荐

