r - 调整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 轴。我该如何执行?
解决方案
如果您想让辅助轴显示不同的比例(或限制),则必须转换数据,例如,您可以将变量(要绘制在 sec 轴上)scales::rescale(Sit, c(0, 21))
重新缩放到变量的范围(要绘制在初级 x 刻度上)。然后你必须使用例如应用逆变换:Sit
Ind
sec_axis
scales::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")
推荐阅读
- python - Python 文件路径
- angular - 设置 cdk-virtual-scroll-viewport 的项目数
- c++ - 试图删除链表的所有元素但得到“错误:AddressSanitizer:heap-use-after-free on address....”
- html - FullCalendar - 使用下拉菜单创建事件
- ios - NSFetchedResultsController 和 NSDiffableDataSourceSnapshot 有什么区别?
- python - 编写一个函数来执行 Collatz 猜想
- excel - 在 Excel 中存储数据
- c++ - 如何将对象数组传递给函数?
- pine-script - 如何根据 ADX 的值使 ADX 变为绿色或红色?
- google-bigquery - 通过 Transfer Jobs 导入 Google Play 收入