knitr::opts_chunk$set(dev = "ragg_png")Custom font in ggplot without using {showtext}
Setup for rendering
Important
This chunk is absolutely necessary for rendering html from Rmd/quarto documents.
For pdf outputs, use “cairo_pdf” device.
None of this is necessary when just executed from R code because the device is managed through RStudio setting (Tools > Global Options > Graphics, AGG must be selected there)
Tip
The options for all kind of outputs can be easily set all at once in the yaml headers of the .Rmd/.qmd file.
format:
# for html outputs
html:
knitr:
opts_chunk:
dev: "ragg_png"
# for PDFs
pdf:
knitr:
opts_chunk:
dev: "cairo_pdf"
# For word document
docx:
knitr:
opts_chunk:
dev: "ragg_png"
dpi: 300
Libraries
library(tidyverse)
library(palmerpenguins)
library(ragg)
library(systemfonts)Load Font
systemfonts::register_font(name = "iaWriter",
plain = "iAWriterQuattroS-Regular.ttf"
)Custom font for plot text
penguins %>%
ggplot(aes(x = bill_length_mm, y = bill_depth_mm, color = species)) +
labs(title = "This is the default ggplot2 font") +
geom_point()Warning: Removed 2 rows containing missing values (`geom_point()`).
penguins %>%
ggplot(aes(x = bill_length_mm, y = bill_depth_mm, color = species)) +
geom_point() +
labs(title = "This is a custom font called iaWriter") +
theme(text = element_text(family = "iaWriter"))Warning: Removed 2 rows containing missing values (`geom_point()`).
Custom font for points
Add fonts
systemfonts::register_font(name = "fontawesome",
plain = "Font Awesome 6 Free-Solid-900.otf"
)
systemfonts::register_font(name = "fontawesome-brands",
plain = "Font Awesome 6 Brands-Regular-400.otf"
)Same symbol for all
penguins %>%
ggplot(aes(x = bill_length_mm, y = bill_depth_mm, color = species)) +
geom_text(label = "dog", family = "fontawesome")+
theme(text = element_text(family = "iaWriter"))Warning: Removed 2 rows containing missing values (`geom_text()`).
Symbol as aesthetic
penguins %>%
mutate(shape = case_when(
species == "Adelie" ~ "linux",
species == "Chinstrap" ~ "twitter",
species == "Gentoo" ~ "earlybirds"
)) %>%
ggplot(aes(x = bill_length_mm, y = bill_depth_mm, color = species)) +
geom_text(aes(label = shape), family = "fontawesome-brands") +
guides(color = guide_legend(override.aes = aes(label = "shapes", alpha = 1, family = "fontawesome"))) +
theme(text = element_text(family = "iaWriter"))Warning: Removed 2 rows containing missing values (`geom_text()`).
Sources
- https://yjunechoe.github.io/posts/2021-06-24-setting-up-and-debugging-custom-fonts/
- https://www.youtube.com/watch?v=EIOo6T-Z1Qw&ab_channel=DavidKeyes