Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 is there an easy way to wrap annotation text?

Tags:

r

ggplot2

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")
like image 552
SkyWalker Avatar asked Aug 03 '14 16:08

SkyWalker


3 Answers

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))
like image 99
Eric Fail Avatar answered Sep 19 '22 13:09

Eric Fail


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) 
like image 42
user20650 Avatar answered Sep 21 '22 13:09

user20650


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
  )
)
like image 32
glenn_in_boston Avatar answered Sep 21 '22 13:09

glenn_in_boston