Is Ggplot2 an easy way to wrap text annotations?

I am currently using ggplot2 and the annotation function, an example from the documentation is given below. I have a limited width to annotate text of unknown length and need an automatic way to wrap it within the x_start and x_end . Since I do not want to change the font size, I will also need to shift the y value depending on how many gaps are entered. Is there an easy way to do 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") 
+6
source share
2 answers

An alternative solution using only base and ggplot2 .

Based on what you specified 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)) 
+3
source

Maybe the splitTextGrob function from the RGraphics package RGraphics . This will wrap the text depending on the width of the chart 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) 
+4
source

Source: https://habr.com/ru/post/973282/


All Articles