0

I'm plotting a group of curves, using facet in ggplot2. I'd like to have a smoother applied to plots where there are enough points to smooth, but not on plots with very few points. In particular I'd like to stop the plot failing when one of the panels only has 1 or 2 points.

Example:

a <- data.frame( x=1:100, y=sin(seq(0.1,10,0.1) )) 
b <- data.frame( x=1:5, y=sin(seq(0.1,0.2,0.1) )) 
l <- melt(list(a=a,b=b),id.vars="x") 
qplot( x, value, data=l ) + geom_smooth() + facet_wrap( ~ L1 )
mo-seph
  • 6,073
  • 9
  • 34
  • 35
  • 1
    Have you checked this question out yet? http://stackoverflow.com/questions/1570379/adding-statsmooth-in-to-only-1-facet-in-ggplot2 – Matt Parker Nov 06 '09 at 15:34
  • Yup. It's not easy to give a subset of the data to the smoother, as it is going to be faceted - I'd have to figure out which of the facets had enough data, and then subset just those facets out of the original data. The colouring doesn't work, as I'm trying to stop the smoother being run at all – mo-seph Nov 06 '09 at 15:46
  • Please provide a small reproducible example – hadley Nov 06 '09 at 16:16
  • a <- data.frame( x=1:100, y=sin(seq(0.1,10,0.1) )) b <- data.frame( x=1:5, y=sin(seq(0.1,0.2,0.1) )) l <- melt(list(a=a,b=b),id.vars="x") qplot( x, value, data=l ) + geom_smooth() + facet_wrap( ~ L1 ) – mo-seph Nov 06 '09 at 16:46
  • Oops, that didn't work, I've added it to the question – mo-seph Nov 06 '09 at 16:48
  • this example code doesn't work. – Eduardo Leoni Nov 06 '09 at 16:51

1 Answers1

4

Try this

library(ggplot2)
a <- data.frame( x=1:100, y=sin(seq(0.1,10,0.1) )) 
b <- data.frame( x=1:2, y=sin(seq(0.1,0.2, length = 2) )) 
l <- melt(list(a=a,b=b),id.vars="x") 

more_than <- function(n) {
  function(df)  {
    if (nrow(df) > n) {
      df
    }
  }
}

lbig <- ddply(l, "L1", more_than(5))

qplot( x, value, data=l ) + geom_smooth() + facet_wrap( ~ L1 )
qplot( x, value, data=l ) + geom_smooth(data = lbig) + facet_wrap( ~ L1 )
hadley
  • 102,019
  • 32
  • 183
  • 245
  • Great! I hadn't used ddply before, or fed different data to geoms. That opens up a whole world of possiblities. Thanks! – mo-seph Nov 07 '09 at 17:07