Save ggplot2 plots with custom fonts using Cairo graphics across OS

The Cairo graphics library makes it easy to embed custom fonts in PDFs and create high resolution PNGs (with either AGG or Cairo).
r
ggplot2
cairo
Author
Published

Sunday, December 3, 2023

Modified

Saturday, December 16, 2023

This content is credited from here.

R and ggplot can create fantastic graphs, but the default Arial/Helvetica font is too boring and standard. You can change the font used in a plot fairly easily three different ways:

  1. All of the built-in ggplot themes have a base_family argument for setting the overall font family for the plot
  2. element_text() has a family argument for changing fonts on individual plot elements
  3. geom_text() and annotate(geom = "text", ...) have a family argument for changing fonts on text layers
# Save the plot as a PDF with ggsave and Cairo
# R will want to autocomplete cairo_pdf to cairo_pdf() (note the parentheses)
# This will not work with the parentheses; ensure there aren't any
ggsave(p, filename = "example.pdf", device = cairo_pdf,
       width = 4, height = 3, units = "in")

# You can also save the plot as a high resolution PNG using 
# AGG or Cairo
# With {ragg}
ggsave(p, filename = "whatever.png",
       device = ragg::agg_png, res = 300,
       width = 4, height = 3, units = "in")

# With Cairo
ggsave(p, filename = "whatever.png",
       device = png, type = "cairo", dpi = 300,
       width = 4, height = 3, units = "in")

Reference