Custom functions for consistent plots

R Programming
Data visualization
Reproducible Research

This lesson introduces participants to creating and applying custom functions in R to ensure consistent formatting across plots. Participants will learn how to bundle preferred theme elements into a reusable function and apply it to their visualizations for cleaner and more uniform results.

Authors

Mary Piper

Meeta Mistry

Radhika Khetani

Jihe Liu

Will Gammerdinger

Noor Sohail

Published

May 30, 2025

Keywords

R, ggplot2, custom themes, plotting functions

Approximate time: 20 minutes

Learning Objectives

  • Apply the custom function to generate consistent plots.

Consistent formatting using custom functions

When publishing, it is helpful to ensure all plots have similar formatting. To do this we can create a custom function with our preferences for the theme. Remember the structure of a function is:

# DO NOT RUN
name_of_function <- function(arguments) {
    statements or code that does something
}

Now, let’s suppose we always wanted our theme to include the following:

# DO NOT RUN
# Themes we will like to include
theme_bw() +
theme(axis.title=element_text(size=rel(1.5))) +
theme(plot.title=element_text(size=rel(1.5), hjust=0.5))
Note

You can also combine multiple arguments within the same theme() function:

# DO NOT RUN
# You can combine all of the theme layers into a single layer
theme_bw() +
theme(axis.title=element_text(size=rel(1.5)), 
      plot.title=element_text(size=rel(1.5), hjust=0.5))

If there is nothing that we want to change when we run this, then we do not need to specify any arguments. Creating the function is simple; we can just put the code inside the {}:

# Create personal theme function for figures
personal_theme <- function(){
  theme_bw() +
  theme(axis.title=element_text(size=rel(1.5))) +
  theme(plot.title=element_text(size=rel(1.5), hjust=0.5))
}

Now to run our personal theme with any plot, we can use this function in place of the lines of theme() code:

# Apply personal theme to figure
ggplot(new_metadata) +
  geom_point(aes(x=age_in_days, y=samplemeans, color=genotype, shape=celltype), size=rel(3.0)) +
  xlab("Age (days)") +
  ylab("Mean expression") +
  ggtitle("Expression with Age") +
  personal_theme()

Reuse

CC-BY-4.0