I'm currently using ggplot2 and the annotate function, an example from the documentation is below. I have limited width to annotate text of unknown length and need an automatic way to wrap it within some x_start
and x_end
values. Since I don't want to change the font size, I will also need to shift the y
value depending on how many breaks are introduced. Is there an easy way to accomplish this?
# install.packages(c("ggplot2"), dependencies = TRUE)
require(ggplot2)
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
p + annotate("text", x = 4, y = 25, label = "Some arbitrarily larger text")
An alternative solution using only base
and ggplot2
.
Building from what you presented above
# First a simple wrapper function (you can expand on this for you needs)
wrapper <- function(x, ...) paste(strwrap(x, ...), collapse = "\n")
# The a label
my_label <- "Some arbitrarily larger text"
# and finally your plot with the label
p + annotate("text", x = 4, y = 25, label = wrapper(my_label, width = 5))
Maybe the splitTextGrob
function from RGraphics
package can help. This will wrap the text depending on the width of the plot window.
library(RGraphics)
library(ggplot2)
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
grob1 <- splitTextGrob("Some arbitrarily larger text")
p + annotation_custom(grob = grob1, xmin = 3, xmax = 4, ymin = 25, ymax = 25)
I use a tidyverse stringr solution similar to Eric Fail, though without the need to create a function (which, neither does Eric's, to be transparent):
# use str_wrap to wrap long text from annotate
p + annotate(
"text", x = 4, y = 25,
label = stringr::str_wrap(
"Some arbitrarily larger text",
width = 20
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With