janosdivenyi janosdivenyi - 17 days ago 5
R Question

How to pipe forward a ggplot object?

I would like to use a custom function defined on a ggplot object with

magrittr
's pipe. However, I cannot pipe a ggplot object into this function.

Here is a simple example:



library(ggplot2)
library(magrittr)

my_plot_function <- function(plot) {
plot + geom_hline(yintercept = 3, linetype = 'dashed')
}

data(mtcars)
p <- mtcars %>%
ggplot() +
geom_point(aes(mpg, wt))
my_plot_function(p)


It would be great if I could use
my_plot_function()
within the chain as follows:

mtcars %>%
ggplot() +
geom_point(aes(mpg, wt)) %>%
my_plot_function()


However, it gives an error as only the layer is passed to
my_plot_function()
instead of the plot itself. How could I pass the plot with the pipe?

Answer

You can try:

my_plot_function <- function(plot) {
    geom_hline(yintercept = 3, linetype = 'dashed')
}


mtcars %>%
    ggplot() +
    geom_point(aes(mpg, wt)) + my_plot_function()
Comments