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.
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.
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:
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}
}