Martin Johnsson's blog

Meny

Using R: a function that adds multiple ggplot2 layers

Another interesting thing that an R course participant identified: Sometimes one wants to make a function that returns multiple layers to be added to a ggplot2 plot. One could think that just adding them and returning would work, but it doesn’t. I think it has to do with how + is evaluated. There are a few workarounds that achieve similar results and may save typing.

First, some data to play with: this is a built-in dataset of chickens growing:

One way is to write a function that takes the plot object as input, and returns a modified version of it. If we use the pipe operator %>%, found in the magrittr package, it even gets a ggplot2 like feel:

Okay, maybe that plot is a bit too busy to be good. But note how the difference between plotting a single diet and all diets at the same time is just one more mapping in aes(). No looping or custom functions required.

Inläggsnavigering

9 thoughts on “Using R: a function that adds multiple ggplot2 layers”

Nice post, and a good illustration of the quirks of adding multiple objects to a plot at once!

I’m not a ggplot expert, but from what I understand from working with it, ggplot2 basically assumes the left-hand side of the ‘+’ operator is always a ggplot object or a ggplot theme, and the right hand side is something you want to add to it. Sequential `+` operators are evaluated in order from left to right, so the left is always a valid ggplot object. The error you’re getting above is because the function ”add_line_points” is getting evaluated together, and ggplot doesn’t know how to add two geoms together in the absence of a ggplot object. You get the same error from just running

try(add_line_points(diet1))

The way you can add multiple ggplot2 parts together in absence of a ggplot() object is to connect them together with a list. So this works as it should:

You are right. But mainly this is how ggplot2 works internally. Your last example is how it should work. You organise your data to be able to group it according to what you want to show. You don’t usually try to plot different data Frames with one ggplot command. The philosophy behind ggplot2 is that you first prepare your data according to what you want to plot and then use the aes() to group it correctly.