This is a note to self

I don’t really like the defaults in ggplot2 and it is super easy to set up a theme that does look how I like (sort of like my burd_jff theme in stata). Walking myself through the process after finishing the themes tutorial on datacamp.



z is just some plot. There are some colors (myPink) defined as well.

# Plot 1: change the plot background color to myPink:
z + theme(plot.background = element_rect(fill = myPink))

# Plot 2: adjust the border to be a black line of size 3
z + theme(plot.background = element_rect(fill = myPink, color = "black", size = 3))

# Plot 3: set panel.background, legend.key, legend.background and strip.background to element_blank()
uniform_panels <- theme(panel.background = element_blank(),
                        legend.key = element_blank(),
                        strip.background = element_blank())

z + theme(plot.background = element_rect(fill = myPink, color = "black", size = 3)) + uniform_panels

Grids and Lines

And now:

  • remove the grid lines with the panel.grid argument.
  • add black axis lines with element_line() with the color argument to specify the axis.line argument.
  • change the tick marks to be black with axis.ticks.
# Extend z with theme() function and three arguments
z + theme(panel.grid = element_blank(), axis.line = element_line(color = "black"), axis.ticks = element_line(color = "black"))


skipping this for now.


Where to put legends?

# Move legend by position
z + theme(legend.position = c(0.85, 0.85))

# Change direction
z + theme(legend.direction = "horizontal")

# Change location by name
z + theme(legend.position = "bottom")

# Remove legend entirely
z + theme(legend.position = "none")


skipping for now.

Saving a Theme

There are built in theme templates such as:

  • theme_classic
  • Use the ggthemes package?

We can also update the default the theme (and this will be applied everywhere). theme_set is probably the way to do this at the top of every program.


p <- ggplot(mtcars, aes(x = wt, y = mpg, col = as.factor(am))) +
  geom_point() +

theme_jjf <- theme(
  # make the background white (blank)
  panel.background = element_blank(),
  # and no ugly legend backgrounds
  legend.background = element_blank(),
  legend.key = element_blank(),
  # and put the legend at the bottom
  legend.position = "bottom",
  # and if the caption is good enough, no legend title
  legend.title = element_blank(),
  # and turn on the axis lines (buggy for now, set x and y sep)
  panel.border = element_blank(),
  axis.line.x = element_line(size = .5, color = "black", linetype = "solid"),
  axis.line.y = element_line(size = .5, color = "black", linetype = "solid")

grid.arrange(p, p + theme_jjf, nrow=2)

p + theme_jjf + scale_fill_brewer(palette="Set1") + scale_color_brewer(palette="Set1")