How to place the same smoothness on each face of the ggplot2 object?

Here is an example:

eg <- data.frame(x = c(1:50, 50:1), y = c(1:50, 1:50) + rnorm(100), g = rep(c("a","b"), each=50)) qplot(x, y, data = eg) + facet_wrap(~ g) + geom_smooth() 

I would like to be able to draw overall smoothness along both sides, as well as have smooth edges.

Edit: here is one way.

 my.smooth <- gam(y ~ s(x), data = eg) my.data <- data.frame(x = 1:50) my.data$y <- predict(my.smooth, newdata = my.data) qplot(x, y, data = eg) + facet_wrap(~ g) + geom_smooth() + geom_smooth(data = my.data) 

Thanks for any help!

Andrew

+4
source share
1 answer

Smart trick: setting the variable cut to NULL

 library(ggplot2) eg <- data.frame(x = c(1:50, 50:1), y = c(1:50, 1:50) + rnorm(100), g = rep(c("a","b"), each=50)) p <- qplot(x, y, data = eg) + facet_wrap(~ g) + geom_smooth() p + geom_smooth(data=within(eg, g <- NULL), fill="red") 

Or if you want, use facet_grid(..., margins=TRUE) :

 p + facet_grid(.~g, margins=TRUE) 
+6
source

All Articles