我需要在ggplot中创建一些游戏图。我可以使用常规绘图功能来完成这些操作,但是不确定如何使用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")

最佳答案

请参阅以下旧答案的更新。

旧答案:
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
r - ggplot的gam绘图-LMLPHP

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

r - ggplot的gam绘图-LMLPHP

您可能还想绘制观察值:
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)}

r - ggplot的gam绘图-LMLPHP

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

r - ggplot的gam绘图-LMLPHP

更新,2020年1月8日。

我目前认为mgcViz软件包比voxel::plotGAM函数提供了更好的功能。使用上述数据集和模型的示例:
library(mgcViz)
viz <- getViz(gam.college)
print(plot(viz, allTerms = T), pages = 1)

r - ggplot的gam绘图-LMLPHP

情节定制类似于go ggplot2语法:
trt <- plot(viz, allTerms = T) +
  l_points() +
  l_fitLine(linetype = 1)  +
  l_ciLine(linetype = 3) +
  l_ciBar() +
  l_rug() +
  theme_grey()

print(trt, pages = 1)

r - ggplot的gam绘图-LMLPHP

vignette显示了更多示例。

关于r - ggplot的gam绘图,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49471300/

10-12 12:42