We all know we can do
p <- ggplot(data)
p + aes(x = funny_hat) + geom_histogram()
But I've never seen documentation of the opposite case. Say I want to store a bunch of ggplot objects, e.g.:
geom_boxplot() + stat_compare_means(method = "anova", size = 14, vjust = 1) +
scale_y_continuous(breaks = seq(-2,2.5, 0.5)) + theme(text = element_text(size = 48))
... so that I can plug all of that in for different datasets e.g.
ggplot(data1) + [all my arguments]
ggplot(data2) + [all my arguments]
This doesn't work if I try to use the same method as I would in the first example, but is there a way to do it? I grow tired of copy-pasting...
The trick is use a list of the elements to make a template, and then apply the template to different data frames:
library(ggplot2)
library(ggpubr)
plot_template <- list(
geom_boxplot(),
stat_compare_means(method = "anova", size = 14, vjust = 1),
scale_y_continuous(breaks = seq(-2, 2.5, 0.5)),
theme(text = element_text(size = 48))
)
# test
ggplot(mtcars, aes(x = factor(gear), y = mpg)) + plot_template
ggplot(iris, aes(x = Species, y = Petal.Length)) + plot_template

You can do this with the (underused/underappreciated) %+% operator, which substitutes a new data object and rebuilds the object.
Building on @TarJae's example,
gg0 <- ggplot(iris, aes(x = Species, y = Petal.Length)) + plot_template
gg0 %+% mtcars + aes(x = factor(gear), y = mpg)
(if you were doing this with a bunch of data sets that all had the same variables you wouldn't need to add the aes(...) to override the previous mappings ...)
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