4

Here's 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'd like to be able to plot the overall smooth on both facets as well as having the facet-specific smooths.

Edit: here's 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

Marek
  • 49,472
  • 15
  • 99
  • 121
  • The examples here should be relevant: http://had.co.nz/ggplot2/geom_smooth.html – Chase Jul 13 '11 at 01:36
  • 2
    schweet, glad you were able to get it figured out. Feel free to answer your own question and then accept it, perfectly legit thing to do. Welcome to SO! – Chase Jul 13 '11 at 03:19

1 Answers1

6

Clever trick: setting the faceting variable 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 prefer, use facet_grid(..., margins=TRUE):

p + facet_grid(.~g, margins=TRUE)
Jon Olav Vik
  • 1,421
  • 2
  • 12
  • 20