I want to find a way to automatically wrap ggplot titles (or subtitles, or captions) to take up the full plot width and then wrap.
A previous question deals with how to wrap code nicely using a wrapper function, but you still have to specify width=
manually. How can I re-write this wrapper function to automatically wrap the text based on the plot width of the plot?
My code so far:
wrapper <- function(x, ...) {
paste(strwrap(x, ...), collapse = "\n")
}
library("ggplot2")
my_title <- "This is a really long title of a plot that I want to nicely wrap and fit the plot width without having to manually add the backslash n, or having to specify with= manually"
ggplot(data = cars, aes(x = speed, y = dist)) +
geom_smooth() +
labs(title = wrapper(my_title, width = 100))
My idea: extract the plot width from ggplot somehow and then include it in the wrapper function, perhaps like this:
plot_width <- ???
wrapper <- function(x) {
paste(strwrap(x, width = plot_width), collapse = "\n")
}
How can I do this?
Or is there a better way?