Ben
Ben

Reputation: 1506

How do I create objects to insert in ggplot (when there are multiple parts with +)?

In my analysis work I use ggplot in R to produce multiple plots. I would like to set my desired plot theme (using ggtheme plus some manual changes) as a single object and then call this theme in each of the plots I produce. I have given an example below.

This code throws an error due to the presence of the + in the definition of my theme object. The ggplot function recognises this symbol as adding new elements, but I am not able to use this symbol when creating a separate THEME object to call in ggplot. Obviously I could transfer the main theme into the ggplot call and just keep my manual changes in THEME, but I would like to have the whole thing in one object for brevity.

#Load libraries
library(ggplot2)
library(ggthemes)

#Create mock data for illustrative purposes
DATA <- data.frame(x = c(3,6,8,11,2,7,4,4,3,6),
                   y = c(12,8,8,4,15,10,9,13,11,6))

#Set theme for plots
THEME <- theme_economist() + scale_colour_economist() +
         theme(plot.title    = element_text(hjust = 0.5),
               plot.subtitle = element_text(hjust = 0.5, face = 'bold'),
               axis.title.y  = element_text(face = 'bold', size = 12),
               plot.margin        = margin(t = 0, r = 20, b = 0))

#Error: Don't know how to add RHS to a theme object

#Generate plot using above theme
FIGURE <- ggplot(data = DATA, aes(x = x, y = y)) +
          geom_point() + THEME
FIGURE

Question: How do I amend my definition of THEME to allow me to specify my theme and changes in a single object that can be called later in ggplot?

Upvotes: 3

Views: 1257

Answers (1)

iod
iod

Reputation: 7592

Wrap your theme calls with list and replace the + with commas:

THEME <- list(theme_economist(), scale_colour_economist(),
         theme(plot.title    = element_text(hjust = 0.5),
               plot.subtitle = element_text(hjust = 0.5, face = 'bold'),
               axis.title.y  = element_text(face = 'bold', size = 12),
               plot.margin        = margin(t = 0, r = 20, b = 0)))

(Note you had a semicolon at the end of the theme() call. Not sure why that was there...)

Upvotes: 4

Related Questions