Search code examples
rpanellatticeloess

Adding a custom LOESS panel to lattice plot in R


I'm trying to create a custom LOESS panel function for my plot. Basically what it should do is the same as a simple panel.loess or type = "smooth". The reason is that later on I want to make it a bit more complicated with things that cannot easily achieved with the above. However, it fails.

Here's a MWE (some of it loosely based on the example at page 235 of Sarkar's Lattice book:

library(lattice)

set.seed(9)
foo <- rexp(100)
bar <- rexp(100)
thing <- factor(rep(c("this", "that"), times = 50))
d.f <- data.frame(foo = foo, bar = bar, thing = thing)

loess.c <- function(x) { 
  mod <- loess(foo ~ bar, data = x)
  return(mod)
}

panel.cloess <- function(x, n = 50, ...){ 
  panel.xyplot(x, ...)
  lfit  <- loess.c(x)
  xx <- do.breaks(range(x$x), n)
  yy <- predict(lfit, newdata = data.frame(bar = xx),
                se = TRUE)
  print(yy) # doesn't do anything
  panel.lines(x = xx, y = yy$fit, ...)
}

xyplot(foo ~ bar | thing, data = d.f,
       panel = panel.cloess)

The result is this:

R output

Obviously, this isn't working. I get the following error message: Error using packet n numeric 'envir' arg not of length one. My attempts at debugging it (e.g. using that print(yy)) do not work as well, so I have no idea where to start looking for a solution.

Any ideas on what's causing this?


Solution

  • after some (small) modifications, I have used this script

    xyplot(foo ~ bar | thing, data = d.f, panel =  function(x,y){
        xx <- do.breaks(range(x), 49)
        mod <- loess(y~x)
        yy <- predict(mod, newdata = data.frame(foo=xx))
        panel.xyplot(x,y)
        panel.lines(x=xx, y= yy)
    })
    

    I have changed the number of points because there was some warning message. Does it work and is that what you were expecting ?