Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving ggplot objects for use on different datasets

Tags:

r

ggplot2

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...

like image 515
purpleblade98 Avatar asked Jun 06 '26 07:06

purpleblade98


2 Answers

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

enter image description here enter image description here

like image 125
TarJae Avatar answered Jun 09 '26 00:06

TarJae


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 ...)

like image 24
Ben Bolker Avatar answered Jun 09 '26 02:06

Ben Bolker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!