首页 > 解决方案 > 调整ggplot2中两个x轴的限制

问题描述

我有以下数据:

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))

library(ggplot2)
ggplot(plot_data) +
        geom_line(aes(x = Sit, y = Ric),
                  color = "blue", lwd = 2) +
        geom_line(aes(x = Ind, 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, y = Ric,
                        ymin = lower, ymax = upper), 
                    linetype = 2, alpha = 0.3, fill = "yellow") +
        scale_x_continuous("Samples", 
                           sec.axis = sec_axis(~ ., 
                                               name = "Individuals"), 
                           limits = c(0, 21)) +
        ylab("Accumulated Richness")

我会将两个 x 轴限制设置为在开始和结束时重合。

我想要限制 0 到 6 的主要 x 轴和 0 到 21 的次要 x 轴。我该如何执行?

标签: rggplot2

解决方案


如果您想让辅助轴显示不同的比例(或限制),则必须转换数据,例如,您可以将变量(要绘制在 sec 轴上)scales::rescale(Sit, c(0, 21))重新缩放到变量的范围(要绘制在初级 x 刻度上)。然后你必须使用例如应用逆变换:SitIndsec_axisscales::rescale(., c(0, 6), c(0, 21))

library(ggplot2)

ggplot(plot_data) +
  geom_line(aes(x = scales::rescale(Sit, c(0, 21)), y = Ric),
    color = "blue", lwd = 2
  ) +
  geom_line(aes(x = Ind, y = Ric),
    color = "red", lwd = 2, lty = 2
  ) +
  geom_ribbon(aes(
    x = scales::rescale(Sit, c(0, 21)), y = Ric,
    ymin = lower, ymax = upper
  ),
  linetype = 2, alpha = 0.3, fill = "yellow"
  ) +
  geom_ribbon(aes(
    x = Ind, y = Ric,
    ymin = lower, ymax = upper
  ),
  linetype = 2, alpha = 0.3, fill = "yellow"
  ) +
  scale_x_continuous("Samples",
    sec.axis = sec_axis(~ scales::rescale(., c(0, 6), c(0, 21)),
      name = "Individuals"
    )
  ) +
  ylab("Accumulated Richness")


推荐阅读