-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1_fonts_errbars.qmd
More file actions
181 lines (146 loc) · 5.84 KB
/
Copy path1_fonts_errbars.qmd
File metadata and controls
181 lines (146 loc) · 5.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
---
title: "Using custom fonts and plotting with error bars"
author: "Michael Stadler, Charlotte Soneson"
format:
html:
toc: true
toc-location: left
embed-resources: true
link-external-icon: true
code-fold: true
editor_options:
chunk_output_type: console
---
## Summary
This document illustrates how to use `systemfonts` and `ragg` together with
`ggplot2` to:
- make a plot that uses custom fonts
- make a plot with error bars
## Prepare data
Run the following code to prepare the data used in this document:
```{r}
#| label: prepare_data
#| code-fold: false
suppressPackageStartupMessages({
library(dplyr)
library(tibble)
})
# built-in `mtcars` dataset (see ?mtcars)
# ... convert some columns to factors
mycars <- mtcars
mycars$cyl <- factor(mycars$cyl, levels = c("4","6","8"))
mycars$engine_shape <- factor(c("0" = "V-shaped", "1" = "straight")[as.character(mycars$vs)])
mycars$transmission <- factor(c("0" = "automatic", "1" = "manual")[as.character(mycars$am)])
# ... summarize power by cylinders
mycars_summary <- mycars |>
group_by(cyl) |>
summarise(hp_avg = mean(hp),
hp_sem = sd(hp) / sqrt(length(hp)),
.groups = "drop")
tibble(mycars)
tibble(mycars_summary)
```
## Create figure
### Load packages
```{r}
#| label: load_packages
library(ggplot2)
library(ragg)
library(systemfonts)
# remark: have to set the chunk output device to "ragg_png"
knitr::opts_chunk$set(dev = "ragg_png")
```
### Get fonts
We first need to make the fonts available to `R`. Either our desired font
is already installed on the local system, or we can download
one of the many free fonts available on the internet, for example from
[https://fonts.google.com/](https://fonts.google.com/).
The `systemfonts` package helps to list locally installed fonts that `R`
can "see" or make a downloaded font file (typically a TrueType file) available
to `R`.
```{r}
#| label: get_fonts
# list available fonts:
fonts <- systemfonts::system_fonts()
fonts
unique(fonts$family)
# download and register an additional font
# ... already registered fonts
systemfonts::registry_fonts()
# ... download Gochi Hand
download.file(url = "https://github.com/huertatipografica/gochi-hand/archive/master.zip",
destfile = file.path(tempdir(), "master.zip"))
extracted_files <- unzip(file.path(tempdir(), "master.zip"), exdir = tempdir())
# ... we typically want a TrueType file (extension `.ttf`)
ttf <- grep(".ttf$", extracted_files, value = TRUE)
ttf
# ... register the newly downloaded font for use in R
systemfonts::register_font(name = "Gochi Hand", plain = ttf)
# ... list the now registered fonts
systemfonts::registry_fonts()
```
### Plot
With the fonts available to `R`, we can now create plots that use custom
fonts for some or all of the text elements. Fonts are defined by
`element_text()` using the arguments `family` (see the `family` column returned
by `systemfonts` functions) and `face` (one of "plain", "italic", "bold" or
"bold.italic", see `style` column return by `systemfonts` functions).
```{r}
#| label: plot
# remember that this will only work if you have
# activated the `ragg` backend to render the plots
# create base plot
p0 <- ggplot(data = mycars, mapping = aes(x = cyl)) +
coord_cartesian(ylim = c(0, 250)) +
labs(x = "Number of cylinders", y = "Gross horsepower") +
theme_bw(20) +
theme(panel.grid = element_blank())
# ... add bars and Roman font
p0 +
geom_col(data = mycars_summary, mapping = aes(y = hp_avg),
fill = "gray70") +
geom_errorbar(data = mycars_summary,
mapping = aes(ymin = hp_avg - hp_sem,
ymax = hp_avg + hp_sem),
width = 0.6) +
annotate("text", x = -Inf, y = Inf, hjust = -0.1, vjust = 1.1,
label = "Question:\nIs this font well readable?",
family = "Z003", size = 18 / .pt) +
theme(text = element_text(family = "Z003"))
# ... add points with errorbars and handwriting-style font
p0 +
geom_pointrange(data = mycars_summary,
mapping = aes(y = hp_avg,
ymin = hp_avg - hp_sem,
ymax = hp_avg + hp_sem),
size = 6,
color = "firebrick") +
geom_point(mapping = aes(y = hp), shape = 1) +
annotate("text", x = -Inf, y = Inf, hjust = -0.1, vjust = 1.1,
label = "Conclusion:\nMore cylinders give\n increased power",
family = "Gochi Hand", size = 18 / .pt) +
annotate("text", x = Inf, y = -Inf, hjust = 1.1, vjust = -0.5,
label = "mean +/- sem", color = "firebrick",
family = "Gochi Hand", size = 18 / .pt) +
theme(text = element_text(family = "Gochi Hand"))
```
## Remarks
The page at https://r-graph-gallery.com/custom-fonts-in-R-and-ggplot2.html
describes two ways to use custom fonts with `ggplot2`:
- [`ragg`](https://ragg.r-lib.org/) is a graphics backend (it renders the plot
to a bitmap graphics device like `png()`), and can make all system fonts
available to be used in R. This is the approach used above. `ragg` is based
on the fast [`AGG`](https://github.com/ghaerr/agg-2.6) library, does not
require you to use any other packages and is also fully integrated into
RStudio (you can select is as your default graphics device in "Tools" ->
"Global options..." -> "General", panel "Graphics").
- [`showtext`](https://github.com/yixuan/showtext) is a package that is
especially designed to use custom fonts with `pdf()` devices. After loading
a font and activating `showtext`, it renders the characters as filled polygons.
Another useful page with more detailed information about using fonts in
`ggplot2` and `R` in general: https://yjunechoe.github.io/posts/2021-06-24-setting-up-and-debugging-custom-fonts/
## Session info
```{r}
#| label: session_info
sessioninfo::session_info()
```