0

The following four calls return what seems to be the exact same graph. How can I control the panel density plot? Thank you.

 library(lattice)
 df <- data.frame( y = runif(100) , p = rep(c('a','b'),50) )

 histogram(~ y | p , data = df , 
      type = "density",
      panel=function(x, ...) {
        panel.histogram(x, ...)
        panel.densityplot(x, ...)
      })


 histogram(~ y | p , data = df , 
      type = "density",
      panel=function(x, ...) {
        panel.histogram(x, ...)
        panel.densityplot(x, bw=100,kernel="gaussian",...)
      })

 histogram(~ y | p , data = df , 
      type = "density",
      panel=function(x, ...) {
        panel.histogram(x, ...)
        panel.densityplot(x, dargs=list(bw=100,kernel="gaussian"),...)
      })

 histogram(~ y | p , data = df , 
      type = "density", bw=100,kernel="gaussian" ,
      panel=function(x, ...) {
        panel.histogram(x, ...)
        panel.densityplot(x, ...)
      })
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
user2105469
  • 1,413
  • 3
  • 20
  • 37
  • Your third code block is almost right, but you made the mistake of writing `dargs` where you need to write `darg`. – Josh O'Brien Jun 10 '14 at 20:54
  • Re. your first comment: this will work `df <- data.frame( y = runif(100) , p = rep(c('a','b'),50) )`. Re. your second comment, the graph stays the same, `dargs` or `darg` but thanks for pointing it out. – user2105469 Jun 10 '14 at 20:56
  • Take a closer look. When you set `bw=100`, the density gets so smoothed out it goes to close to zero everywhere. Set `bw=1` with the sample data you gave me, and you'll see the difference. – Josh O'Brien Jun 10 '14 at 21:00
  • I ran the bottom three graphs with bw=1 and there's no change in the plot. I cleared the plots area (RStudio), started again, no change. Which syntax did you use to observe the change ? – user2105469 Jun 10 '14 at 21:05
  • I copy-pasted your code below in my local R window, and it worked. – user2105469 Jun 10 '14 at 21:33

1 Answers1

3

As mentioned in comments above, your third call to histogram() was very close. You just needed to write darg instead of dargs.

Here's an example to show that darg does indeed, as documented in ?panel.densityplot, give you control over the smoothing parameters:

library(gridExtra)  ## For grid.arrange()
library(lattice)
df <- data.frame(y = runif(100) , p = rep(c('a','b'),50))

p1 <- histogram(~ y | p , data = df , 
          type = "density",
          panel=function(x, ...) {
             panel.histogram(x, ...)
             panel.densityplot(x, darg=list(bw = 1, kernel="gaussian"),...)
      })

p2 <- histogram(~ y | p , data = df , 
          type = "density",
          panel=function(x, ...) {
              panel.histogram(x, ...)
              panel.densityplot(x, darg=list(bw = 0.2, kernel="gaussian"),...)
      })

grid.arrange(p1,p2)

enter image description here

Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455