Plotting estimates using ggplot2 & facet_wrap WITHOUT re-fitting models

拥有回忆 提交于 2019-12-11 00:33:45

问题


I am pretty new to ggplot2 and am looking to produce a figure with multiple scatter plots with their respective regression estimates. However I am using non-standard regression approaches (e.g quantile regression and total regression) that are not among the list of method arguments available in geom_smooth(). I have a list of fitted models and corresponding data. Below is a working example.

require(data.table); require(ggplot2)
N <- 1000 # Generate some data
DT <- NULL
models <- list() # list of of fitted models. For simplicity i am using lm in this example
for(i in 1:8){
  x <- rnorm(N)
  y <- i*x + rnorm(N)
  z <- rep(i,N)
  DT <- rbind(DT,data.table(cbind(x=x,y=y,z=z)))
  models[[i]] <- lm(y~x,DT)
}

# Traditional way to plot the data with regression estimates is to use geom_smooth
my.plot <- ggplot(DT, aes(x=x, y=y)) + geom_point() + 
  facet_wrap(~ z, nrow=2, ncol=4) + 
  geom_smooth(method = "lm", se=FALSE, color="red", formula = y ~ x)
my.plot

I need a way to plot the red regression estimates without fitting regression models within geom_smooth. Is there a work around that would make my separate list of fitted Models compatible with facet_wrap?


回答1:


Because it's not clear how you'll be mapping aesthetics to variables used in your model, you'll need to calculate the values for the lines yourself and then just add them as a standard geom_line layer rather than using geom_smooth. For example

lines <- purrr::map_dfr(models, function(m) {
  xrng <- range(m$model$x)
  data.frame(x=xrng, y=predict(m, data.frame(x=xrng)))
}, .id="z")

ggplot(DT, aes(x=x, y=y)) + geom_point() + 
  facet_wrap(~ z, nrow=2, ncol=4) + 
  geom_line(color="red", data=lines)

Note that the slopes look a bit "off" here but this matches what you actually modeled (you used the entire DT each time). If you wanted to estimate the slopes separately in each iteration, you loop should have looked more like

for(i in 1:8){
  x <- rnorm(N)
  y <- i*x + rnorm(N)
  z <- rep(i,N)
  chunk <- data.table(x=x,y=y,z=z)
  models[[i]] <- lm(y~x,chunk)
  DT <- rbind(DT, chunk)
}


来源:https://stackoverflow.com/questions/54563723/plotting-estimates-using-ggplot2-facet-wrap-without-re-fitting-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!