SkyWalker
SkyWalker

Reputation: 14317

ggplot2 is there an easy way to wrap annotation text?

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")

Upvotes: 10

Views: 5590

Answers (3)

glenninboston
glenninboston

Reputation: 1045

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
  )
)

Upvotes: 5

Eric Fail
Eric Fail

Reputation: 7948

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))

Upvotes: 5

user20650
user20650

Reputation: 25914

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) 

Upvotes: 6

Related Questions