Skip to contents

Given an existing ggplot2 object, shade an area under an existing density curve.

Usage

shadeRange(
  plot,
  range = list(list(lower = NA, upper = 0.1, alpha = 0.3, colour = "goldenrod1"),
    list(lower = 0.9, upper = NA, alpha = 0.3, colour = "goldenrod1")),
  idx = 2
)

Arguments

plot

The ggplot2 object

range

a vector (or list of vectors) containing the definition(s) of the range(s) to be shaded. See Usage Notes below.

idx

An integer defining the index within the list returned by ggplot2::ggpot_build that identifies the layer containing the density to be shaded. Typically, this corresponds to the order in which the various geoms are added to the ggplot2 object. For example, in d %>% ggplot2() %>% geom_point(...) %>% geom_density(...), idx should be 2`.

Value

The modified ggplot2 object

Usage Notes

range should be a list or a list of vectors. If a list, it should contain named elements lower, upper, alpha and colour, where lower and upper contain the lower and upper x axis values that define the extent of the shaded area, colour defines the colour of the shaded area and alpha defines the alpha value that defines the transparency of the shading. An alpha of 0 denotes complete transparency (or invisibility). An alpha of 1 denotes total opacity, meaning that the contents of any layers below the density will be invisible if within the shaded area.

To define shaded ranges that include the left- or right-most extents of the density, set lower or upper respectively to NA.

If a list of lists, each element of the list should be a list with elements as defined above.

For example, the default value of range defines the ranges to be shaded as those that lie below the 10th centile or above the 90th centile of the density in goldenrod1 using an alpha of 0.3.