Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: apply customization from variable

Tags:

r

ggplot2

I'm new to R and ggplot2. How would I go about applying a customization to multiple plots? I thought I could just store the customization in a variable but this does not work:

# customization <- theme_bw() + xlab("time")
x <- 1:20
y <- dnorm(x, 10, 5)
y2 <- dnorm(x, 10, 2)
p1 <- ggplot() + geom_line(aes(x,y)) # + customization
p2 <- ggplot() + geom_line(aes(x,y2)) # + customization

Now I would like to apply customization to both plots without copy/pasting the two additional settings.

like image 338
mxm Avatar asked May 24 '26 05:05

mxm


1 Answers

You can put the theme elements in one object and the labels in another object and then combine them with +. This isn't quite as succinct as what you were probably hoping for, but maybe it gets you part of the way there. If you have more than one label and several theme elements, it will save you some typing. For example:

x <- rep(1:20,2)
y <- c(dnorm(x[1:20], 10, 5), dnorm(x[21:40], 20, 5))
group = factor(rep(c("A","B"),each=20))
dat=data.frame(x,y,group)

opt <- theme(title=element_text(size=18, colour="green"),
             axis.text=element_text(size=13, colour="black"),
             axis.title=element_text(size=15, colour="blue"),
             legend.title=element_text(colour="black")) 
lab <- labs(x="Time", y="Value", colour="Group", title="Plot Title")

ggplot(dat) + geom_line(aes(x,y, colour=group)) + opt + lab

UPDATE: Per @ Baptiste's comment, you can combine the theme and labs elements in a single list object:

custom <- list(opt, lab)

ggplot(dat) + geom_line(aes(x,y, colour=group)) + custom
like image 173
eipi10 Avatar answered May 26 '26 02:05

eipi10



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!