Search code examples
rggplot2themescustomizationlegend

Include guide() in ggplot2 theme


Our organization has a very exacting style book, so I've been tasked with creating a ggplot theme that programmers can use to ensure that their charts and graphs are as close as possible to "official" style.

One of the requirements is that the legend for a graph be below the graph, but vertically stacked, like this:

Example of acceptable pie chart

I've been generating graphics like this in the following way:

pie_theme <- theme(
    text = element_text(family = "Arial", face = "bold", size = 7, color = "black"),
    plot.caption = element_text(hjust = 0, size = 6),
    legend.position = "bottom",
    etc.
    )
    
    p1 <- ggplot(bla bla bla)+geom_bar(bla bla bla)+coord_polar(bla bla bla)
    
    p1+ guides(fill=guide_legend(ncol=1)) +
      pie_theme

Ideally, I'd like to integrate the guides() command into the theme so that programmers don't have to add the guides() every time they output a chart and the legend automatically stacks vertically. But I don't see a theme() attribute that will do that. Any advice?

Thank you!


Solution

  • The + operation for ggplot objects and lists work such that every element of the list is added to the plot seperately. For this to work, you can just wrap the theme and guides in a list, which you can then add just like you would a regular theme.

    A word of warning though, if you map a continuous variable to the guide, it will try to pick guide_legend() instead of guide_colorbar(), which is arguably more appropriate, if you use it in this way.

    library(ggplot2)
    
    pie_theme <- list(
      theme(
        text = element_text(face = "bold", size = 7, color = "black"),
        plot.caption = element_text(hjust = 0, size = 6),
        legend.position = "bottom"
      ),
      guides(fill = guide_legend(ncol = 1))
    )
    
    ggplot(mtcars, aes(x = factor(1), fill = factor(cyl))) +
      geom_bar(width = 1) +
      coord_polar(theta = "y") +
      pie_theme
    

    Created on 2020-12-23 by the reprex package (v0.3.0)