Thursday, March 6, 2025

Using special fonts in R plots

For a paper in CEUR format, I wanted to change the fonts of the figures in the paper to the "Libertinus" font, which is used in the CEUR template. Some figures were created as graph plots in R. MS Copilot suggested using the extrafonts package in R, which did not work. 

Here's what worked instead. I copied the ttf file of the font to a fonts subdirectory and added this to my rmd script:

library(showtext)

font_add("Libertinus Sans", "fonts/LibertinusSans-Regular.ttf")  # Use the actual file path

showtext_auto()


Then, in each ggplot statement, I added the font name in the theme parameters:

ggplot(knowledge_stats, aes(x=item, y=median, group=survey, fill=survey))+

  geom_bar(stat="identity", position="dodge")+

  facet_grid(.~departement)+

  scale_fill_manual(values = c("steelblue1", "grey80"))+

  labs(title=paste("ASE: Knowledge gain", subtitle="L: 6 persons, T: 32"))+

  theme_bw()+

  theme(text = element_text(family = "Libertinus Sans"),plot.title = element_text(size=14), legend.title=element_text(size=16), legend.text=element_text(size=12),

          axis.title.x=element_blank(), axis.title.y=element_text(size=16), 

          axis.text.x=element_text(size=14, angle = 90), axis.text.y=element_text(size=14), legend.position="bottom",

        strip.text.x=element_text(size=12), strip.text.y=element_text(size=12), 

        )


Using 

ggsave("ase_knowledge_gain.pdf", units="cm", width=16, height=12)

the font was correctly used in the generated PDF file.