Making text labels the same size as axis labels in ggplot2

The geom_text and geom_label functions do not specifiy text size the same way as the rest of ggplot2 elements do. For consistent text sizes, we can apply a simple conversion.
ggplot2
Author
Affiliation
Published

August 10, 2021

As explained in this ggplot2 vignette, the size parameter in geom_text and geom_label is in millimeters, and the size parameter in all other text elements in ggplot2 is in points.

If I specify the base_size of the plot and the size of a label to 16, you can see that the text label is much bigger than 16.

library(tidyverse)
textsize <- 16
ggplot() +
  stat_function(
    fun = dnorm,
    xlim = c(-4, 4),
    geom = "area",
    alpha = .3
  ) +
  theme_minimal(base_size = textsize) +
  annotate(
    geom = "text",
    x = 0,
    y = 0,
    label = "Mean = 0",
    size = textsize,
    vjust = -.1
  )

If you do not mind a little trial and error, you can fiddle with the size parameter until you find a value that looks good to you. However, what if we want the axis text labels and the output of geom_text to be exactly the same size?

We are in luck because ggplot2 has a .pt constant that will help us convert point sizes to millimeters.

ggplot2::.pt
[1] 2.845276

We know that, by default, axis text is .8 times as large as the base_size of the theme.

Let’s make a function to automate the conversion:

ggtext_size <- function(base_size, ratio = 0.8) {
  ratio * base_size / ggplot2::.pt
}

Now we can make the label and axis text exactly the same size:

ggplot() + 
  stat_function(fun = dnorm, xlim = c(-4,4), geom = "area", alpha = .3) +
  theme_minimal(base_size = textsize) + 
  annotate(
    geom = "text",
    x = 0,
    y = 0,
    label = "Mean = 0",
    size = ggtext_size(textsize),
    vjust = -.3
  )

For my own convenience (and possibly yours), I put the ggtext_size function in the WJSmisc package.

For more on ggplot font size matters, I found this post by Christophe Nicault to be informative.

Citation

BibTeX citation:
@misc{schneider2021,
  author = {Schneider, W. Joel},
  title = {Making Text Labels the Same Size as Axis Labels in Ggplot2},
  date = {2021-08-10},
  url = {https://wjschne.github.io/posts/making-text-labels-the-same-size-as-axis-labels-in-ggplot2},
  langid = {en}
}
For attribution, please cite this work as:
Schneider, W. J. (2021, August 10). Making text labels the same size as axis labels in ggplot2. Schneirographs. https://wjschne.github.io/posts/making-text-labels-the-same-size-as-axis-labels-in-ggplot2