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:
This single component can be placed inside the syntax of the grammar of graphics and used as a plot layer.
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
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: