mxm
mxm

Reputation: 615

ggplot2: apply customization from variable

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.

Upvotes: 3

Views: 113

Answers (2)

eipi10
eipi10

Reputation: 93881

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

Upvotes: 1

Jaap
Jaap

Reputation: 83275

You can just combine it together in one plot like this:

ggplot() + 
  geom_line(aes(x,y), color="red") + 
  geom_line(aes(x,y2), color="blue") + 
  theme_bw() + xlab("time")

which gives: enter image description here

Upvotes: 0

Related Questions