Skip to content

Instantly share code, notes, and snippets.

@expersso
Created September 12, 2018 08:58
Show Gist options
  • Save expersso/29f82285fbbd0f2006f7a2f4482576e4 to your computer and use it in GitHub Desktop.
Save expersso/29f82285fbbd0f2006f7a2f4482576e4 to your computer and use it in GitHub Desktop.
Function for adding units to axis labels
library(tidyverse)
add_units <- function(p, unit, scale = "x", outside = TRUE) {
params <- ggplot_build(p)$layout$panel_params[[1]]
if(scale == "x") {
brks <- params$x.major_source
scale <- scale_x_continuous
} else {
brks <- params$y.major_source
scale <- scale_y_continuous
}
idx <- if(outside) length(brks) else 1
names(brks) <- brks
names(brks)[idx] <- paste(brks[idx], unit)
suppressMessages(p + scale(breaks = brks))
}
p <- ggplot(iris, aes(x = Petal.Length, y = Sepal.Width, color = Species)) +
geom_point() +
theme(axis.text.x = element_text(hjust = 0)) +
labs(x = "Petal Length", y = "Sepal Length", title = "Iris")
p %>%
add_units("cm", "x") %>%
add_units("cm", "y")
@expersso
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment