Created
April 26, 2019 18:24
-
-
Save bschneidr/ca133251ee0beb3089d15e3c0e1fef2b to your computer and use it in GitHub Desktop.
Example of how to make ggplot2 labels wrap to fit device size when printing the plot
This file contains hidden or 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(ggplot2) | |
# This function will udpate the ggplot2 print method used in the session | |
wrap_labels_in_print_method <- function (dev_scaler = 12) { | |
if (!"ggplot2" %in% .packages()) { | |
stop("The ggplot2 package must be installed and loaded.") | |
} | |
# This is a custom printing function that will update wrapping in plot labels | |
# to match the width of the current device. (in RStudio, this is the 'Plots' pane) | |
wrap_title_to_device <- function(ggplot_obj, dev_scaler) { | |
dev_width <- dev.size("in")[1] | |
ggplot_obj[['labels']] <- lapply(ggplot_obj[['labels']], | |
function(x) paste(strwrap(x, | |
width = dev_width*dev_scaler), | |
collapse = "\n")) | |
gridExtra::grid.arrange(ggplot_obj) | |
} | |
# Overwrites the default ggplot2 print method | |
custom_print_method <- wrap_title_to_device | |
formals(custom_print_method)$dev_scaler <- dev_scaler | |
print_copy <- get("print.ggplot", envir = asNamespace("ggplot2")) | |
environment(custom_print_method) <- environment(print_copy) | |
attributes(custom_print_method) <- attributes(print_copy) | |
assignInNamespace("print.ggplot", custom_print_method, ns = "ggplot2") | |
} | |
# Apply the function | |
wrap_labels_in_print_method(dev_scaler = 12) | |
# Create an example plot | |
p <- ggplot(mtcars) + | |
geom_point(aes(x = wt, y = mpg), color = "dodgerblue4") + | |
labs(title = "This is a very long title that is meant to exemplify what happens when you try to wrap the labels in a plot object.") | |
# Print the plot | |
print(p) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment