3

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.

5
  • Can you make your code easier for us to run by using sample datasets? Commented Jun 13, 2014 at 16:48
  • I changed the example since it was a bit confusing. I commented out the code which did not run. Hope this makes my question more clear to you. Commented Jun 13, 2014 at 17:01
  • I think the solution to this question is way deeper and more complicated than the effort it takes to copy and paste the customizatin. The "+" sign is a S3 method (see ggplot2:::+.gg) Commented Jun 13, 2014 at 18:08
  • 2
    p2 + list(theme_bw(), xlab("time")) Commented Jun 13, 2014 at 19:19
  • That's what I had in mind! Commented Jun 13, 2014 at 22:07

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

That was not the point of my question but in general it is worth to consider combining plots with the same settings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.