{camcorder}
doesn’t only work with raster
images such as PNG and JPEG but also PDF files. There are some benefits
of using the PDF format when saving ggplot output: vector graphics are
lossless, can be converted easily in raster formats of any
resolution and also be manipulated afterwards in a vector design tool.
Furthermore, the PDF format often supports the use of custom fonts (when
using the Cairo device)1.
To automatically save your graphics in PDF format, just change the
device setting to cairo_pdf
2 when recording your
ggplot code:
library(ggplot2)
library(camcorder)
gg_record(
dir = file.path(tempdir(), "recording"),
device = cairo_pdf, # we need to set the Cairo device
width = 8,
height = 5
)
Mac users should ensure that XQuartz is installed which is needed to use the cairo pdf device.
To supply custom fonts in R, the respective font needs to be installed locally on the system.
You can make sure the font file is installed by using the
system_fonts()
from the latest standard, the
{systemfont}
package:
systemfonts::system_fonts()
#> # A tibble: 148 × 9
#> path index name family style weight width italic monospace
#> <chr> <int> <chr> <chr> <chr> <ord> <ord> <lgl> <lgl>
#> 1 /usr/share/fonts/type… 0 URWG… URW G… Book… normal norm… FALSE FALSE
#> 2 /usr/share/fonts/true… 0 Libe… Liber… Bold bold norm… FALSE FALSE
#> 3 /usr/share/fonts/type… 0 Nimb… Nimbu… Bold… bold norm… TRUE TRUE
#> 4 /usr/share/fonts/true… 0 Libe… Liber… Bold bold norm… FALSE TRUE
#> 5 /usr/share/fonts/open… 0 Nimb… Nimbu… Bold… bold norm… TRUE FALSE
#> 6 /usr/share/fonts/type… 0 Nimb… Nimbu… Regu… normal norm… FALSE FALSE
#> 7 /usr/share/fonts/type… 0 Nimb… Nimbu… Ital… normal norm… TRUE FALSE
#> 8 /usr/share/fonts/type… 0 Nimb… Nimbu… Bold… bold norm… FALSE FALSE
#> 9 /usr/share/fonts/type… 0 D050… D0500… Regu… normal norm… FALSE FALSE
#> 10 /usr/share/fonts/X11/… 0 P052… P052 Bold… bold norm… TRUE FALSE
#> # ℹ 138 more rows
You can simply filter this tibble for any font:3
systemfonts::system_fonts() |>
dplyr::filter(grepl("Dyna", family)) |>
dplyr::pull(name) |>
sort()
#> character(0)
Now let’s create a graphic with the DynaPuff Condensed typeface as
the base_family
of our theme:
g <-
ggplot(diamonds, aes(x = cut)) +
geom_bar(fill = "grey65") +
theme_minimal(
base_family = "DynaPuff Condensed",
base_size = 24
)
g
And now let’s add a non-condensed, bold title:
g +
ggtitle("PDFs are a font lovers best friend") +
theme(
plot.title.position = "plot",
plot.title = element_text(family = "DynaPuff", face = "bold")
)
That’s it. If you want to know more about good practices how to
handle and customize fonts in {ggplot2}
check this blog
post by June Choe.
Thanks to the {ragg}
package custom font
support is working quite well for raster images now—but it’s not a
vector graphic 🙃↩︎
Cairo is an open-source graphics library that is known to work very well with custom fonts.↩︎
To make the difference obvious we use the fun, quirky font DynaPuff which is freely available.↩︎