我正在尝试使用grid.arrange()
将线性回归图及其诊断图放入一张图中。为了创建诊断图,我将使用autoplot()
library(gridExtra)
library(ggplot2)
linearMod <- lm(dist ~ speed, data=cars)
qqp <- (autoplot(linearMod, which = 2)) # qqplot
rvf <- (autoplot(linearMod, which = 1)) # res vs fitted plot
grid.arrange(qqp, rvf, nrow = 2)
> Error in `$<-`(`*tmp*`, wrapvp, value = vp) :
no method for assigning subsets of this S4 class
显然,自动绘图会创建类型为S4
的ggmultiplot,但我找不到将其转换为grob的方法,而使用grid.arrange()
则需要。
我尝试过:
library(ggplotify)
as.grob(qqp)
> Error in UseMethod("as.grob") :
no applicable method for 'as.grob' applied to an object of class "ggmultiplot"
as.grob(qqp@plots) # also failed...
有人知道解决方案吗?自动绘图的诊断图是否可以替代或与其他绘图结合使用?
感谢您的任何帮助!
ggplot2
类对象的调用autoplot
autoplot
正在创建一个类对象ggmultiplot
,其中包含以ggplot格式显示的绘图。
> summary(qqp)
Length Class Mode
1 ggmultiplot S4
但是,您必须调用此ggplot
才能在grid.arrange
中使用。通过您的示例,您可以执行以下操作:
library(ggfortify)
library(gridExtra)
grid.arrange(qqp@plots[[1]], rvf@plots[[1]], nrow = 2)
使用ggplot2
重新创建由autoplot
制作的图
或者,您可以使用dplyr
(或其他方法)提取拟合值和残差值并直接获取ggplot:
library(tidyverse)
library(gridExtra)
CARS <- cars[,c("speed","dist")] %>% mutate(Fitted = linearMod$fitted.values, Residual = linearMod$residuals)
a <- ggplot(CARS, aes(x = Fitted, y = Residual))+
geom_point()+
stat_smooth(se = FALSE)
b <- ggplot(CARS, aes(sample = dist)) + stat_qq() + geom_qq_line(linetype = "dashed")
grid.arrange(b,a, nrow = 2, ncol = 1)
希望它可以帮助您解决问题