Description
I often find myself making plots where I want to include some sort of label near the plot margin. Usually I would use geom_text, but sometimes I have a figure (imagery or heatmap, for example) where the text isn't visible without a background, so I use geom_label in those cases. However, I have found that the alignment of the text and background box in geom_label don't behave in a way that I would expect or that is conducive to making tidy looking figures. Here is an example of putting the labels in the lower, left-hand corner without changing the justification. As expected, the labels run off the page and the text is centered within the background box.
library(tibble)
library(dplyr)
library(ggplot2)
df <- tibble(group = c(rep(1, 4), rep(2, 4)),
x = rep(seq(1, 4), 2)) %>%
mutate(y = case_when(group == 1 ~ 2*x,
group == 2 ~ -2*x + 10))
labels <- tibble(group = seq(1, 2),
x = rep(min(df$x), 2),
y = rep(min(df$y), 2),
label = c('A nice, long label goes here', 'short label'))
plot <- ggplot(df, aes(x = x, y = y)) +
geom_line() +
facet_grid(. ~ group)
plot +
geom_label(data = labels,
aes(x = x, y = y,
label = label),
size = 2)
I can change hjust
and vjust
so that the label is aligned in the lower left corner. However, with a smaller than default text size, and a non-centered justification, the text is not centered within the background box. Personally, I think this looks bad, and also results in more of the figure being covered up by the background box than is necessary.
# Adding labels, the text isn't centered in the box (this is more obvious if the text size is reduced)
plot +
geom_label(data = labels,
aes(x = x, y = y,
label = label),
size = 2,
hjust = 0,
vjust = 0)
Using nudge_x
and nudge_y
instead of hjust
and vjust
allows the text to remain centered within the background box, but requires more fiddling to get the text location correct when the labels are all the same length. When the labels are not all the same length, this method does not allow the desired alignment - either the longer label runs off the left side of the plot or the shorter label is pushed farther toward the center of the figure.
# the text is centered within the box, but labels of different lengths aren't aligned in the bottom, left corner
plot +
geom_label(data = labels,
aes(x = x, y = y,
label = label),
size = 2,
nudge_x = 1,
nudge_y = 0.25)
Ideally, I think the text in a geom_label should be centered within it's background box regardless of the value of hjust
or vjust
.