library(tidyverse)
<- 16
textsize 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
)
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.
::.pt ggplot2
[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:
<- function(base_size, ratio = 0.8) {
ggtext_size * base_size / ggplot2::.pt
ratio }
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
@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}
}