I am attempting to create a ggplot2 plot where I set the font for all text elements, including labels on the bars (geom_col), to "LM Roman 10". One could also use another font like "Calibri". The font for axis labels is displaying correctly as is should be: "LM Roman 10", but the labels on the bars still appear in the default R font despite using extrafont and setting the font for the entire plot.
data <- data.frame(
Year = 2010:2021,
Value = c(8031, 8554, 8124, 7859, 8026, 8326, 8606, 8184, 8332, 8111, 6764, 6439)
)
library(ggplot2)
library(extrafont)
library(scales)
ggplot(data, aes(x = Year, y = Value, fill = as.factor(Year))) +
geom_col(fill = "#7f7f7f", width = 0.5) +
geom_text(aes(label = format(Value, big.mark = '.', scientific = FALSE)),
position = position_dodge(width = 0.9), size = 3.5, colour = 'black', vjust = -0.5) +
scale_y_continuous(limits = c(0, 10000), labels = scales::comma_format(big.mark = '.')) +
scale_x_continuous(name = "Year", limits = c(2009.5, 2021.5), breaks = seq(2010, 2021, by = 1)) +
labs(x = NULL, y = "Number of Units", title = NULL) +
theme_bw(base_size = 14, base_family = "LM Roman 10") +
theme(legend.position = "none", panel.grid = element_blank())
The font "LM Roman 10" should be applied to all text elements in the plot, including the text labels above the bars.
Axis labels are correctly displayed in "LM Roman 10", but the text labels above the bars (geom_text) are shown in the default R font.
How can I ensure that the "LM Roman 10" font is used for all text elements in the plot, including the labels of geom_col?
Thanks for reading. Luckily I found the solution myself.
The trick is, to manipulate the geom_text() with
geom_text(family = "font")