首页 > 解决方案 > 如何安排拟合的 GAM 图并在 R 中包含有关图的摘要信息?

问题描述

我有两个拟合的 GAM 模型,它们代表两个站点,每个模型都有两个自变量。我想将生成的四个 GAM 图排列成一个 2 列 2 行的图(见下面的例子)。顶行代表一个站点的模型结果,底行代表第二个站点的模型结果。所有 y 轴都具有相同的变量,因此我希望沿左列只有一个 y 轴标题,同时保留两个独立的 x 轴标题。一旦安排了这些 GAM 图,我想包括 Adj。R2 值和站点名称与地块。

library(mgcv)

df1 <- data.frame(x1 = rnorm(50), x2 = rnorm(50), y1 = rnorm(50))
df2 <- data.frame(x1 = rnorm(50), x2 = rnorm(50), y2 = rnorm(50))

df1$Site <- "Site1"
df2$Site <- "Site2"

m1 <- gam(y1 ~ s(x1) + s(x2), data = df1)
m2 <- gam(y2 ~ s(x1) + s(x2), data = df2)

p1 <- plot(m1)
p2 <- plot(m2)

summary(m1) # This is where the Adj. R2 value comes from for m1
summary(m2) # This is where the Adj. R2 value comes from for m2

我尝试过使用p1/p2 + plot_layout(ncol = 2, heights = c(1,1))但得到了Error in p1/p2 : non-numeric argument to binary operator,我也尝试过使用grid.arrange(p1,p2, ncol = 2)但得到了错误Error in gList(list(list(x = c(-2.390381407938, -2.3411392450022, -2.29189708206641, : only 'grobs' allowed in "gList"

最终我想要一个看起来像这样的数字: 在此处输入图像描述

标签: rggplot2plotgammgcv

解决方案


我想建议可以由gam 对象visreg生成的库:ggplotmgcv

library(mgcv)
library(visreg)
library(grid)
library(gridExtra)
library(ggplot2)

set.seed(101)
df1 <- data.frame(x1 = rnorm(50), x2 = rnorm(50), y1 = rnorm(50))
df2 <- data.frame(x1 = rnorm(50), x2 = rnorm(50), y2 = rnorm(50))

df1$Site <- "Site1"
df2$Site <- "Site2"

m1 <- gam(y1 ~ s(x1) + s(x2), data = df1)
m2 <- gam(y2 ~ s(x1) + s(x2), data = df2)


# Setting some ggplot style here
ggstyle <- theme_classic()+
              theme(axis.text = element_text(color = "black"))

# Covariates of model m1
p1 <- visreg(m1, "x1", gg = TRUE, plot = TRUE) +
          ggstyle +
          labs(title = "Model 1") 

p2 <- visreg(m1, "x2", gg = TRUE, plot = TRUE)+
          ggstyle

# Covariates of model m2
p3 <- visreg(m2, "x1", gg = TRUE, plot = TRUE)+
          ggstyle +
          labs(title = "Model 2") 

p4 <- visreg(m2, "x2", gg = TRUE, plot = TRUE)+
          ggstyle 


    # Aggregate plots
grid.arrange(arrangeGrob(p1, p2, p3, p4, ncol = 2,
             left = textGrob("Global Y-axis Label", rot = 90, vjust = 1)))

结果:

在此处输入图像描述


此外,如果您愿意,可以visreg为 covariate生成一个x1包含数据和拟合的对象:

p1 <- visreg(m1, "x1", gg = TRUE, plot = FALSE)

之后您可以轻松使用ggplot

ggplot()+
  geom_point(data = p1$res, aes(x1, visregRes), shape = 21, size = 3, fill = "#2ca25f")+
  geom_line(data = p1$fit, aes(x1, visregFit))+
  geom_line(data = p1$fit, aes(x1, visregLwr), linetype = 3)+
  geom_line(data = p1$fit, aes(x1, visregUpr), linetype = 3)+
  theme_classic()

在此处输入图像描述


推荐阅读