与ggplot

时间:2018-03-25 00:12:51

标签: 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")

1 个答案:

答案 0 :(得分:12)

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)}

发生一系列错误后: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

enter image description here

plot.gam

进行比较
par(mfrow=c(2,3))
plot(gam.college, se=TRUE,col="blue")

enter image description here

您可能还想绘制观察值:

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)}

enter image description here

或每组(如果您使用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)}

enter image description here