I am curious what people think of this behaviour. Is this intended? Is there a better way to solve this? Feels like it could be a bug if it wasn't such an obvious application.
library(ggplot2)
library(magrittr)
## "normal" way of doing this
p <- ggplot(iris, aes(x = Petal.Width, y = Petal.Length)) +
geom_point()
ggsave("foo.png", plot = p)
#> Saving 7 x 5 in image
## Doesn't work even though it feels like it should. What geom_point returns
## is what is passed to ggsave
p_save <- ggplot(iris, aes(x = Petal.Width, y = Petal.Length)) +
geom_point() %>%
ggsave("foo2.png", plot = .)
#> Saving 7 x 5 in image
#> Error in UseMethod("grid.draw"): no applicable method for 'grid.draw' applied to an object of class "c('LayerInstance', 'Layer', 'ggproto', 'gg')"
## Instead you have to surround the whole ggplot2 call in parens
p_save_parens <- (ggplot(iris, aes(x = Petal.Width, y = Petal.Length)) +
geom_point()) %>%
ggsave("foo3.png", plot = .)
#> Saving 7 x 5 in image
Created on 2020-03-12 by the reprex package (v0.3.0)