7

I'm trying to simplify my plots in ggplot2. Suppose I want to create a scatterplot from iris dataset:

ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
  geom_point()

Iris scatterplot

But suppose I don't like ggplot2 default theme and palette. Let's say I want to use theme_bw and Dark2 palette:

ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
  geom_point() +
  theme_bw() +
  scale_color_brewer(palette="Dark2")

Iris scatterplot with another colour palette

And suppose I have lots of plots and I want all of them using theme_bw and Dark2 palette. I know I can use theme_set(theme_bw()) to make all my plots have the black and white theme. Is there a similar function to make all my plots use Dark2 palette? In other words, how can I run a code like

ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
  geom_point()

and have theme_bw and Dark2 palette in all my plots?

0

2 Answers 2

4

One solution would be to write a custom wrapper:

ggcust <- function(...){
  ggplot(...) +
    theme_bw()
}

fill in all the theme options you need, then use it like this:

ggcust(data = mtcars, aes(x = mpg, y = cyl)) +
  geom_point()

enter image description here

2
  • Since I wanted both theme and palette, I had to add a line with scale_color_brewer(palette="Dark2") in your suggested code, but it worked. Thanks. Jun 7, 2018 at 12:37
  • 1
    Yeah, you can fill in anything you need within the wrapper, I just wanted to keep the example simple. Glad it helped.
    – LAP
    Jun 7, 2018 at 12:43
3

You can also put layers into a list:

gglayer_theme <- list(
  theme_bw(),
  scale_color_brewer(palette="Dark2")
)

And treat the list like a new layer (Note + becomes , in this list notation):

ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
  geom_point() +
  gglayer_theme

The advantage to the custom wrapper approach is the ability to easily mix layers:

gglayer_labs <- list( 
  labs(
    x = "x",
    y = "y"
  )
)

ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
  geom_point() +
  gglayer_theme +
  gglayer_labs

Or combine them beforehand:

gglayer_all <- c(gglayer_theme, gglayer_labs)

ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
  geom_point() +
  gglayer_all

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.