rggplot2

Use markdown in theme element after setting a complete theme


Sometimes users want to use settings from a ggplot complete theme (theme_minimal, for instance) and then manually set another theme element afterwards by calling theme().

For instance, this works

library(tidyverse)
library(ggtext)

ggplot(
  economics, aes(date, unemploy)
  ) + 
  geom_line() +
  scale_x_date(
    breaks = seq.Date(
      "1970-01-01" %>% as.Date,
      "2012-01-01" %>% as.Date, 
      length.out = 5
      ),
    labels = str_c(
      "**",
      seq(1970, 2010, by  = 10),
      "**"
      )
  ) +
  theme(
    axis.text.x =  element_markdown()
  ) 

enter image description here

(with a simplified example of markdown in the axis labels -- I know I could just set axis labels to be bold in theme, this is just a simplified example.)

Now trying to use theme_minimal() and then use theme(), none of the theme() settings work:

ggplot(
  economics, aes(date, unemploy)
  ) + 
  geom_line() +
  scale_x_date(
    breaks = seq.Date(
      "1970-01-01" %>% as.Date,
      "2012-01-01" %>% as.Date, 
      length.out = 5
      ),
    labels = str_c(
      "**",
      seq(1970, 2010, by  = 10),
      "**"
      )
  ) +
  theme_minimal() +
  theme(
    axis.text.x =  element_markdown()
  ) 

enter image description here

how do I set a theme() element after using a ggplot complete theme?


Solution

  • With help from @teunbrand, this is a new... design choice?... shipping with ggplot2 4.0 and their use of S7 internals.

    the fix -- use axis.text.x.bottom

    library(tidyverse)
    library(ggtext)
    
    ggplot(
      economics, aes(date, unemploy)
    ) + 
      geom_line() +
      scale_x_date(
        breaks = seq.Date(
          "1970-01-01" %>% as.Date,
          "2012-01-01" %>% as.Date, 
          length.out = 5
        ),
        labels = str_c(
          "**",
          seq(1970, 2010, by  = 10),
          "**"
        )
      ) +
      theme_minimal() +
      theme(
        axis.text.x.bottom =  element_markdown()
      ) 
    

    enter image description here