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?
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.
%>% 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.
Elements that are normally added to a ggplot with operator + , such as scales, themes, aesthetics can be replaced with the %+% operator.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With