绘制在函数中创建的所有图,并具有显示置信区间 (r) 所需的最小 y 轴范围

问题描述 投票:0回答:1

假设我有代码来生成和保存多个

gam()
模型的绘图,如下所示:

library(mgcv)
library(gratia)
library(tidyverse)

iterate = function(z){

model1 <- gam(mpg ~ cyl +
                       s(disp, k = 25) + wt, data = mtcars %>% dplyr::filter(carb == z), method = "REML")


gam_plot <- draw(model1,
                     ci_col = "red",
                     smooth_col = "red")

assign(paste0("gam_plot", z),gam_plot,envir = .GlobalEnv)

}

z_list = unique(mtcars$gear)


sapply(X = z_list,FUN = iterate)

生成并保存所有这些图后,我想使用

ggarrange()
将所有图绘制在一起,但由于输出相同,我需要在 y 轴上使用特定限制,使两者都不会太窄,以至于阴影置信区间消失,但也不会太宽以致图变得难以理解。在不阻止置信区间被着色的情况下,将所有图的
scale_y_continuous
设置为包含所有图的最窄可能的最有效方法是什么?这是否需要在用于创建和绘制绘图的函数之前通过一个函数来计算,或者这一切都可以在一个函数运行中完成吗?

r ggplot2 sapply
1个回答
0
投票

一个可能的选择是首先创建绘图列表。在第二步中,获取我使用

layer_scales
的 y 尺度范围,并计算“范围”的
range
。最后将组合范围应用于每个图,然后再组合它们:

library(mgcv)
#> Loading required package: nlme
#> This is mgcv 1.9-1. For overview type 'help("mgcv-package")'.
library(gratia)
library(tidyverse)

iterate <- function(z) {
  model1 <- gam(mpg ~ cyl +
    s(disp, k = 3) + wt, data = mtcars %>%
    dplyr::filter(gear == z), method = "REML")


  draw(model1,
    ci_col = "red",
    smooth_col = "red"
  )
}

z_list <- unique(mtcars$gear)

plot_list <- lapply(z_list,iterate)
#> Warning in newton(lsp = lsp, X = G$X, y = G$y, Eb = G$Eb, UrS = G$UrS, L = G$L,
#> : Fitting terminated with step failure - check results carefully

range_y <- plot_list |> 
  lapply(
    \(x) layer_scales(x)$y$range$range
  ) |> 
  unlist() |> 
  range()

plot_list |> 
  lapply(\(x) {
    x +
      scale_y_continuous(limits = range_y)
  }) |> 
  ggpubr::ggarrange(plotlist = _, nrow = 1)

© www.soinside.com 2019 - 2024. All rights reserved.