ggplot - Create a theme

Problem

To be sure to have a consistent style accross many ggplot charts, it is easy to create a theme which is then quickly apply to every graph.

Solution

A theme is a function returning an element theme(). This element theme can take many parameters from: https://ggplot2.tidyverse.org/reference/theme.html

Let’s just put a pink background and a yellow grid.

mytheme <- function() {
  theme(panel.background = element_rect(fill = "pink"),
        panel.grid.major = element_line(colour = "yellow"))
}

ggplot(data, aes(x=patient, y=value)) + geom_col() +
  mytheme()

More

We can chain multiple themes with +, either in the theme definition or in the chart creation. For example we can use the built in theme_minimal() to start clean and build on top of it.

mytheme <- function() {
  theme_minimal() +
  theme(panel.background = element_rect(fill = "pink"),
        panel.grid.major = element_line(colour = "yellow"))
}

ggplot(data, aes(x=patient, y=value)) + geom_col() +
  mytheme()

How can we help?

Whether you already know about your data pain points or just want to have a friendly conversation, send us a message and tell us who you are.