Created
September 12, 2018 08:58
-
-
Save expersso/29f82285fbbd0f2006f7a2f4482576e4 to your computer and use it in GitHub Desktop.
Function for adding units to axis labels
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) | |
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") |
Author
expersso
commented
Sep 12, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment