Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pipe forward a ggplot object?

Tags:

r

pipe

ggplot2

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?

like image 411
janosdivenyi Avatar asked Nov 16 '16 16:11

janosdivenyi


People also ask

Can you pipe into ggplot?

The %>% operator can also be used to pipe the dplyr output into ggplot. This creates a unified exploratory data analysis (EDA) pipeline that is easily customizable. This method is faster than doing the aggregations internally in ggplot and has the added benefit of avoiding unnecessary intermediate variables.

What does %>% do in ggplot?

%>% is a pipe operator reexported from the magrittr package. Start by reading the vignette. Adding things to a ggplot changes the object that gets created. The print method of ggplot draws an appropriate plot depending upon the contents of the variable.

Which operator allows you to add objects to a ggplot?

Elements that are normally added to a ggplot with operator + , such as scales, themes, aesthetics can be replaced with the %+% operator.

What is the first argument in the ggplot () function?

The first argument is the source of the data. The second argument maps the data components of interest into components of the graph. That argument is a function called aes(), which stands for aesthetic mapping.


1 Answers

You can try to define a function that does not expect a plot object and just add it as is usual in ggplot.

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


mtcars %>%
    ggplot() +
    geom_point(aes(mpg, wt)) + my_plot_function()
like image 117
DatamineR Avatar answered Sep 23 '22 11:09

DatamineR