Search code examples
rggplot2themesggrepel

How to let geom_text inherit theme specifications? (ggplot2)


Is there an elegant way in ggplot2 to make geom_text/geom_label inherit theme specifications like a base_family?

Or asked the other way round: Can I specify a theme that also applies to geom_text/geom_label?


Example:

I want text/labels to look exactly like the axis.text as specified in the theme...

Obviously I could add the specifications manually as optional arguments to geom_text, but I want it to inherit the specifications "automatically"...

library("ggplot2")

ggplot(mtcars, aes(x = mpg,
                   y = hp,
                   label = row.names(mtcars))) +
  geom_point() +
  geom_text() +
  theme_minimal(base_family = "Courier")

<code>theme</code> specifications not inherited

Addition: A solution that works with ggrepel::geom_text_repel/geom_label_repel as well would be perfect...


Solution

  • You can

    Setting Overall font

    Firstly, depending on the system you will need to check which fonts are available. As I am running on Windows I am using the following:

    install.packages("extrafont")
    library(extrafont)
    windowsFonts() # check which fonts are available
    

    The theme_set function lets you specify the overall themes for ggplot. So therefore theme_set(theme_minimal(base_family = "Times New Roman")) lets you define the fonts for the plot.

    Make Labels Inherit Font

    To make the labels inherit this text, there are two things we need to use:

    1. update_geom_defaults lets you update the geometry object styling for future plots in ggplot: http://ggplot2.tidyverse.org/reference/update_defaults.html
    2. theme_get()$text$family extracts the font of the current global ggplot theme.

    By combining these two, the label styles can be updated as follows:

    # Change the settings
    update_geom_defaults("text", list(colour = "grey20", family = theme_get()$text$family))
    update_geom_defaults("text_repel", list(colour = "grey20", family = theme_get()$text$family))
    

    Results

    theme_set(theme_minimal(base_family = "Times New Roman"))
    
    # Change the settings
    update_geom_defaults("text", list(colour = "grey20", family = theme_get()$text$family))
    
    # Basic Plot
    ggplot(mtcars, aes(x = mpg,
                       y = hp,
                       label = row.names(mtcars))) +
      geom_point() +
      geom_text()
    

    enter image description here

    # works with ggrepel
    update_geom_defaults("text_repel", list(colour = "grey20", family = theme_get()$text$family))
    
    library(ggrepel)
    
    ggplot(mtcars, aes(x = mpg,
                       y = hp,
                       label = row.names(mtcars))) +
      geom_point() +
      geom_text_repel()
    

    enter image description here