18.1 Programming single and multiple components

In ggplot2 it is possible to build up plot components easily. This is a good practice to reduce duplicated code.

Generalising code allows you with more flexibility when making customised plots.

18.1.1 Components

One example of a component of a plot is this one below:

bestfit <- geom_smooth(
  method = "lm", 
  se = FALSE, 
  colour = alpha("steelblue", 0.5), 
  size = 2)

This single component can be placed inside the syntax of the grammar of graphics and used as a plot layer.

ggplot(mpg, aes(cty, hwy)) + 
  geom_point() + 
  bestfit

Another way is to bulid a layer passing through build a function:

geom_lm <- function(formula = y ~ x, colour = alpha("steelblue", 0.5), 
                    size = 2, ...)  {
  geom_smooth(formula = formula, se = FALSE, method = "lm", colour = colour,
    size = size, ...)
}

And the apply the function layer to the plot

ggplot(mpg, aes(displ, 1 / hwy)) + 
  geom_point() + 
  geom_lm(y ~ poly(x, 2), size = 1, colour = "red")

The book points out attention to the “open” parameter . A suggestion is to use it inside the function instead of in the function parameters definition.

Instead of only one component, we can build a plot made of more components.

geom_mean <- function() {
  list(
    stat_summary(fun = "mean", geom = "bar", fill = "grey70"),
    stat_summary(fun.data = "mean_cl_normal", geom = "errorbar", width = 0.4)
  )
}

Whit this result:

ggplot(mpg, aes(class, cty)) + geom_mean()