Search code examples
rggplot2

Creating function for ggplots with identical formatting


I'm creating a mega-plot that is really 4 different ggplots mashed together, using a dataframe that contains results for 4 different outcomes.

As of now, I've just got these all being created separately, but it's annoying when I have to go change some option for a color or something and need to do it 4 times. Is there a way to make this happen in a more succinct way via a function or something similar?

Here's some simplified figure code for 2 plots, I can include data if needed:

p1 <- logit_results %>%
  filter(outcome == "Time_Sport",
         term != "(Intercept)") %>%
  ggplot(aes(x = estimate, y = term)) +
  geom_point(aes(color = treat), 
             size = 2) +  
  facet_wrap(~ treat, nrow = 2,
             labeller = as_labeller(condition_labels)) + 
  labs(title = "Time for sports")

p2 <- logit_results %>%
  filter(outcome == "Money_Sport",
         term != "(Intercept)") %>%
  ggplot(aes(x = estimate, y = term)) +
  geom_point(aes(color = treat), 
             size = 2) +  
  facet_wrap(~ treat, nrow = 2,
             labeller = as_labeller(condition_labels)) + 
  labs(title = "Money for sports")

p1+p2

Solution

  • For the specific case of substituting in a different data set, you can use the %+% operator. I would do this as follows:

    p0 <- logit_results %>%
      filter(outcome == "Time_Sport", term != "(Intercept)") %>%
      ggplot(aes(x = estimate, y = term)) +
      geom_point(aes(color = treat), size = 2) +  
      facet_wrap(~ treat, nrow = 2,
                 labeller = as_labeller(condition_labels))
    
    p1 <- p0 + labs(title = "Time for sports")
    money_data <- logit_results %>% filter(outcome == "Money_Sport", term != "(Intercept)")
    p2 <- p0 %+%  money_data +  labs(title = "Money for sports")
    
    p1+p2
    

    My general strategy is to set up a "0-level" plot that has only the parts that will be common to all the downstream plots and then add the subplot-specific bits to it. You can obviously automate/modularize this further by wrapping things in functions ...

    For what it's worth you can also use an aes() statement to override previously specified mappings:

    gg0 <- ggplot(aes(mpg, cyl), data = mtcars) + geom_point()
    gg0 + (gg0 + aes(y = hp))
    

    (although this particular example would be better achieved through reshaping the data and then faceting ...)