Graphics Reference
In-Depth Information
Solution
Define a new wrapper function around your curve function, and replace out-of-range values with
NA (), as shown in Figure 13-6 :
# Return dnorm(x) for 0 < x < 2, and NA for all other x
dnorm_limit <- function
function (x) {
y <- dnorm(x)
y[x < 0 | x > 2 ] <- NNA
return
return (y)
}
# ggplot() with dummy data
p <- ggplot(data.frame(x = c( -3 , 3 )), aes(x = x))
p + stat_function(fun = dnorm_limit, geom = "area" , fill = "blue" , alpha = 0.2 ) +
stat_function(fun = dnorm)
Figure 13-6. Function curve with a shaded region
Remember that what gets passed to this function is a vector, not individual values. If this function
operated on single elements at a time, it might make sense to use an if/else statement to decide
Search WWH ::




Custom Search