Last active
October 27, 2021 20:02
-
-
Save fubits1/e71203b53e8bd503a4ebd9a9ae403de7 to your computer and use it in GitHub Desktop.
ggplot2 hack: annotate a single axis-label and preserve intendation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tidyverse) | |
annotation <-"HP" | |
# identify max char length of y-label | |
ymax_chr <- nchar(as.integer(max(mtcars$hp))) | |
ggplot(mtcars, aes(x = mpg, y = hp)) + | |
geom_point(color = "black", alpha = 0.5) + | |
scale_y_continuous( | |
# 1. explicitly define the axis breaks | |
breaks = seq(0,350,50), # needed to ensure that the label we want to extend is shown, also see coord_cartesian() | |
labels = function(x) { | |
labels <- x # vector of ALL y-axis labels | |
# 2. optional, for hjust = 0 approach: left-pad all labels that'd be shorter than the max label value | |
# labels[-length(labels)] <- sprintf(fmt = paste0("%0",ymax_chr,"s"), labels[-length(labels)]) | |
# 3. right-pad all but the last item with xx em (depends on width of annotation string) | |
## see https://jkorpela.fi/chars/spaces.html for other unicode whitespace elements / widths | |
labels[-length(labels)] <- paste0(labels[-length(labels)], "\U2006\U2001\U2000")# "___" ) # 1/6em + 1em + 0.5em | |
# 4. add annotation to to the last label value | |
labels[length(labels)] <- paste0(labels[length(labels)], " ", annotation) | |
return(labels) | |
} | |
) + | |
coord_cartesian(ylim = c(0,350)) + # helps if you need to ensure that the desired y label is shown | |
labs(y = NULL) + # want we want to make obsolete, after all | |
theme_minimal() + | |
theme( | |
## axis.text.y = ggtext::element_markdown( | |
## interpretes hjust differently, as of 2021-10-21 has trouble with <pre>) | |
axis.text.y = element_text( | |
hjust = 1, | |
margin = margin(r = -0.4, unit = "cm"), | |
# fill = "white" # works only for ggtext afaik | |
) | |
) |
Caution: stable with svg(), png() and ragg::agg_png(); doesn't 100% work (for me) with svglite(). svglite ignores the whitespace padding hack
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result: