与ggplot的gam情节

Mar*_*ahr 5 r ggplot2 gam

我需要在ggplot中创建一些gam图.我可以用普通的绘图功能来完成它们,但我不确定如何处理ggplot.这是我的代码和情节与常规绘图功能.我正在使用ISLR包中的College数据集.

train.2 <- sample(dim(College)[1],2*dim(College)[1]/3)
train.college <- College[train.2,]
test.college <- College[-train.2,]
gam.college <- gam(Outstate~Private+s(Room.Board)+s(Personal)+s(PhD)+s(perc.alumni)+s(Expend)+s(Grad.Rate), data=train.college)
par(mfrow=c(2,2))
plot(gam.college, se=TRUE,col="blue")
Run Code Online (Sandbox Code Playgroud)

mis*_*use 14

voxel库中使用ggplot2实现了GAM绘图.以下是你将如何做到这一点:

library(ISLR)
library(mgcv)
library(voxel)
library(tidyverse)
library(gridExtra)
data(College)

set.seed(1)
train.2 <- sample(dim(College)[1],2*dim(College)[1]/3)
train.college <- College[train.2,]
test.college <- College[-train.2,]
gam.college <- gam(Outstate~Private+s(Room.Board)+s(Personal)+s(PhD)+s(perc.alumni)+s(Expend)+s(Grad.Rate), data=train.college)

vars <- c("Room.Board", "Personal", "PhD", "perc.alumni","Expend", "Grad.Rate")

map(vars, function(x){
  p <- plotGAM(gam.college, smooth.cov = x) #plot customization goes here
  g <- ggplotGrob(p)
}) %>%
  {grid.arrange(grobs = (.), ncol = 2, nrow = 3)}
Run Code Online (Sandbox Code Playgroud)

在一堆错误之后: In plotGAM(gam.college, smooth.cov = x) : There are one or more factors in the model fit, please consider plotting by group since plot might be unprecise

在此输入图像描述

要比较plot.gam:

par(mfrow=c(2,3))
plot(gam.college, se=TRUE,col="blue")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

您可能还想绘制观察值:

map(vars, function(x){
  p <- plotGAM(gam.college, smooth.cov = x) +
    geom_point(data = train.college, aes_string(y = "Outstate", x = x ), alpha = 0.2) +
    geom_rug(data = train.college, aes_string(y = "Outstate", x = x ), alpha = 0.2)
  g <- ggplotGrob(p)
}) %>%
  {grid.arrange(grobs = (.), ncol = 3, nrow = 2)}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

或者每组(特别重要的是如果你使用了by参数(gam中的交互).

map(vars, function(x){
  p <- plotGAM(gam.college, smooth.cov = x, groupCovs = "Private") +
    geom_point(data = train.college, aes_string(y = "Outstate", x = x, color= "Private"), alpha = 0.2) +
    geom_rug(data = train.college, aes_string(y = "Outstate", x = x, color= "Private"  ), alpha = 0.2) +
    scale_color_manual("Private", values = c("#868686FF", "#0073C2FF")) +
    theme(legend.position="none")
  g <- ggplotGrob(p)
}) %>%
  {grid.arrange(grobs = (.), ncol = 3, nrow = 2)}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述