# Simplified code
plot +
facet_wrap(
. ~ facetting_var,
ncol = 1,
scales = "free_y",
strip.position = "left"
)
scale_x_discrete(labels = function(x) {
glue(
"<span style='font-size:5pt'>
AREA<br></span>**{x}**"
)
}) +
theme(
strip.background = element_rect(color = "orange", fill = "orange"),
strip.text.y.left = element_text(color = "white", angle = 0, face = "bold"),
axis.title.x = element_text(hjust = 0.4),
axis.text.y = element_blank(),
axis.text.x = ggtext::element_markdown(
color = "gray",
family = "Lato"
),
panel.spacing = unit(0.75, "lines")
)Annotation and axis label tweaks in ggplot2
data-visualisation
ggplot2
r-how-to
Optimising label placement in facetted graphs
Here’s a section of a faceted ggplot dataviz I’ve been working on today for an rfortherest client. Making use of a few handy scale_x_discrete() and theme() tweaks to make the labels line up nicely with the wider aesthetic.
Styling axis text on the fly with a custom function
On the x axis, the labels are "AREA<linebreak><Area number>", with the number using a larger font size than the word “area”. Here’s the relevant code snippet behind that:
Placing the x axis at the top of the graph
And here’s the other modification to help with readability: placing the x-axis at the top, so it reads more like a table.
This required me to modify axis.text.top.x inside theme() because axis.text.x no longer applied.
# Simplified relevant bits of code
plot +
scale_x_discrete(
expand = expansion(add = c(0.5, 2.5)),
position = "top",
labels = function(x) {
glue::glue(
"<span style='font-size:5pt'>{soil_type}<br></span>**{x}**"
)
}
) +
theme(
axis.text.x.top = ggtext::element_markdown(
color = "gray",
family = "Lato"
)
)Every day an #rstats school day!
Reuse
Citation
For attribution, please cite this work as:
Thompson, Cara. 2022. “Annotation and Axis Label Tweaks in
Ggplot2.” August 25, 2022. https://www.cararthompson.com/posts/2022-08-25-talking-of-annotations-heres-a/.

