TIL what happens if you use %>% instead of + in ggplot2

This post is about ggplot2 and dplyr packages, so let’s start with loading them:

[sourcecode language=”r”]
library(ggplot2)
library(dplyr)
[/sourcecode]

I can’t be the first person to make the following mistake:

[sourcecode language=”r”]
ggplot(mtcars, aes(x = wt, y = mpg)) %>%
geom_point()
[/sourcecode]

Can you spot the mistake in the code above? Look closely at the end of the first line.

The operator should be the + used in ggplot2 for layering, not the %>% operator used in dplyr for piping, like this:

[sourcecode language=”r”]
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point()
[/sourcecode]

So what happens if you accidentally use the pipe operator instead of the +? You get the following error:

Error in get(x, envir = this, inherits = inh)(this, ...) : 
 Mapping should be a list of unevaluated mappings created by aes or aes_string

My Google search for this error did not yield my careless mistake as a potential cause. Since many people use these two packages together, I’m guessing such mix-up of operators can’t be too uncommon (right? I can’t be the only one…). So I’m leaving this post here for the next person who makes the same mistake.

 

9 thoughts on “TIL what happens if you use %>% instead of + in ggplot2

  1. Pingback: TIL what happens if you use %>% instead of + in ggplot2 | Mubashir Qasim

  2. Yes, you are the only one 😉
    – still nice to leave the error message for search engines to find.
    Much appreciated from my future me!
    Cheers,
    Bernhard

  3. Piping does work with ggplot2, but you have to wrap geoms and other terms in magrittr::add():

    library(dplyr)
    library(magrittr)
    library(ggplot2)
    mtcars %>%
    ggplot(aes(x = wt, y = mpg)) %>%
    add(geom_point())

  4. Hadley Wickham, last night at the Statistical Programming DC meetup, actually brought this up. ggplot2 was from the pre-magrittr era, and he was trying to get his layering semantics down and chose “+” as his design choice. As he said, if magrittr happened earlier, he could have used ggplot (the original) with it and never developed ggplot2.

  5. Hope this post doesn’t start a flame war. Choice of symbols for operator overload is a touchy subject. This can only get worse when you throw pipeR as well as magritteR into the mix. My ideal solution would be to convince R-dev team to put a pipe operator into the base package and deprecate all add-on pipe packages.

Leave a Reply

Your email address will not be published. Required fields are marked *