views:

153

answers:

1

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 )
+4  A: 

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
Great! I hadn't used ddply before, or fed different data to geoms. That opens up a whole world of possiblities. Thanks!
mo-seph