Search code examples
rggplot2magrittr

Use . notation inside geoms


I want to use the . notation to use the original dataframe (since, sometimes, I haven't defined it in a small variable) inside my geoms. The following doesn't work :

iris %>% ggplot(aes(Sepal.Length, Sepal.Width)) + geom_point(data = subset(.,Sepal.Length < 6))

Error in subset(., Sepal.Length < 6) : object '.' not found

I want the . to point to iris.


Solution

  • Unfortunately I don’t think there’s an elegant solution for it due to how %>% evaluates its right-hand side. However, the following works:

    iris %>% {
        ggplot(., aes(Sepal.Length, Sepal.Width)) +
            geom_point(data = filter(., Sepal.Length < 6))
    }
    

    Note that with this notation you need to explicitly specify . as the first argument to each function using it, including ggplot.