r - 如何安排拟合的 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"
解决方案
我想建议可以由gam 对象visreg
生成的库:ggplot
mgcv
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()
推荐阅读
- sql - 是否可以在 CASE 语句的 UPDATE SET 子句中使用 AND?
- python - 如何将不同的国家语言(NLS)读入python?
- javascript - 带有 for 循环 switch 语句的 FizzBuzz
- c# - 更新 DynamicData nuget 包时遇到问题
- assembly - 递归调用时核心转储程序集失败
- python - 如何从箱线图数据中删除系列?
- forms - 检查在 Powershell 中关闭 Windows 窗体的原因
- c# - 如何在数据网格视图表上显示单选按钮的值
- batch-file - 日志文件读取和查找值字符串
- xcode - xcode 启用推送通知