ggplot font customization
code
beginner
r
ggplot
You can set ggplot’s font using the theme
function. Particularly if combined with functions from ggthemes
or ggsci
you can get very pleasing visualizations quickly. Beyond accessing fonts already on your system you can import and fonts with minimal hassle.
e.g. to get the font Metal Mania ready to use one might run:
library(showtext)
font_add_google(name = "Metal Mania", family = "Metal+Mania")
library(palmerpenguins)
library(tidyverse)
library(ggthemes)
library(patchwork) # for adding together plots at the end
library(extrafont)
# font_import()) # <--- run this once
loadfonts(device = "win", quiet = TRUE) # <--- run this once per session
# extrafont::fonts() # see fonts that are available
<- palmerpenguins::penguins %>%
plt1 filter(!<http://is.na|is.na>(sex)) %>%
mutate(sex = case_when(sex == "male" ~ "m",
== "female" ~ "f")) %>%
sex ggplot(aes(sex, body_mass_g, fill = species, group = interaction(species, sex)))+
geom_boxplot()+
::scale_fill_colorblind()+
ggthemes::theme_clean()+
ggthemestheme(legend.position = "")+
facet_grid(.~species)+
labs(title = "Default")
<- plt1+
plt2 theme(text = element_text(family = "Consolas"))+
labs(title = "Consolas")
<- plt1+
plt3 theme(text = element_text(family = "Garamond"))+
labs(title = "Garamond")
+ plt2 + plt3 plt1