Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bschneidr/5936fe47d19aec036cb69b0b40905310 to your computer and use it in GitHub Desktop.
Save bschneidr/5936fe47d19aec036cb69b0b40905310 to your computer and use it in GitHub Desktop.
Updates ggplot2 print method to wrap labels in plot to match device width
library(ggplot2)
# 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 = 12) {
# Retrieve width of current device in inches
dev_width <- dev.size("in")[1]
# Wrap text in labels
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 to use the custom print method
custom_print_method <- wrap_title_to_device
formals(wrap_title_to_device)$dev_scaler <- 12
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")
# Create an example plot
# 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.")
# The text will wrap based on the device size at the time when the plot is printed
print(p)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment