rggplot2dplyrggthemes

GGPlot2 Preset - Creating a function with certain ggplot2 aesthetics options


I'm creating quite a few plots at the moment. Since they're all geared towards the same presentation, they have a lot in common in terms of the options I chose to give them their appearance.

df1 <- data.frame(name = c("name1","name2","name3","name4"),
                  variable = c("var1","var1","var2","var2"),
                  value = c(15,16,17,18))

df1 %>%
  ggplot(aes(x = name, y = value, fill = variable)) +
  geom_bar(stat = "identity", position = position_stack()) +
  labs(title = "Plot Title",
       subtitle = "month 1",
       x="",
       y="Count") +
  scale_fill_viridis_d(name = "", option = "inferno", begin = 0.3, end = 0.7, direction = -1) +
  scale_shape_tableau() +
  theme_economist() +
  theme(plot.background = element_rect(fill = "white"), 
        plot.title = element_text(hjust = 0.5),
        plot.subtitle = element_text(hjust = 0.5),
        axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1),
        plot.margin = unit(c(1,1,1,1), "cm"))

With the mindset of reducing the number of lines of code, is there a way to create a function with some of those options, such as "theme", "theme_economist", "scale_shape", "scale_fill"? I could then just specify the aesthetics and the labs for each plot, and the rest would just amount to a "+ preset function", to add the themes, colors and shapes.


Solution

  • You can store things to be added to a plot in a list. You can then re-use this list by adding it to a plot.

    library(ggplot2)
    library(ggthemes)
    library(magrittr)
    
    common_options <- list(
      scale_fill_viridis_d(name = "", option = "inferno", begin = 0.3, end = 0.7, direction = -1),
      scale_shape_tableau(),
      theme_economist(),
      theme(plot.background = element_rect(fill = "white"), 
            plot.title = element_text(hjust = 0.5),
            plot.subtitle = element_text(hjust = 0.5),
            axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1),
            plot.margin = unit(c(1,1,1,1), "cm"))
    )
    
    
    
    df1 <- data.frame(name = c("name1","name2","name3","name4"),
                      variable = c("var1","var1","var2","var2"),
                      value = c(15,16,17,18))
    
    df1 %>%
      ggplot(aes(x = name, y = value, fill = variable)) +
      geom_bar(stat = "identity", position = position_stack()) +
      labs(title = "Plot Title",
           subtitle = "month 1",
           x="",
           y="Count") +
      common_options
    

    Created on 2021-07-20 by the reprex package (v1.0.0)