Search code examples
rplotlattice

Color area under curve with Lattice


I would like to color/shade the area between two intervals under a normal curve, such the one produced in the example. An interval could be 125:140 or the segment beyond 140.

library(lattice)

e4a <- seq(60, 170, length = 10000)
e4b <- dnorm(e4a, 110, 15)
xyplot(e4b ~ e4a,
   type = "l",
   scales = list(x = list(at = seq(60, 170, 5)), rot = 45),
   panel = function(x, ...){
           panel.xyplot(x, ...)
           panel.abline( v = c(110, 125, 95, 140, 80, 95), lty = 2)
   })

enter image description here

I found a really straightforward solution for the R graphic base system, but I did not find an equivalent solution for Lattice.


Solution

  • panel.polygon exists:

    xyplot(e4b ~ e4a,
           type = "l",
           scales = list(x = list(at = seq(60, 170, 5)), rot = 45),
           panel = function(x,y, ...){
               panel.xyplot(x,y, ...)
               panel.abline( v = c(110, 125, 95, 140, 80, 95), lty = 2)
    
               xx <- c(125, x[x>=125 & x<=140], 140) 
               yy <- c(0,   y[x>=125 & x<=140], 0) 
               panel.polygon(xx,yy, ..., col='red')
           })
    

    A bit messy with getting the polygon correct.

    Note that e4a is sorted in your data. If that were not so, you would likely need to sort them prior to presenting to panel.polygon.

    enter image description here