wrapping long geom_text labels

Viewed 7936

I have an issue with wrapping long texts in ggplot2. Similar question was asked here ggplot2 is there an easy way to wrap annotation text?

My question is if we have the text like this

my_label <- "Some_arbitrarily_larger_text"

How can we shrink it using the same method ?

wrapper <- function(x, ...) paste(strwrap(x, ...), collapse = "\n")

library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()+
annotate("text", x = 4, y = 25, label = wrapper(my_label, width = 5))

enter image description here

It seems not working for this case!

2 Answers

You can also call stringr::str_wrap(), for:

library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()+
  annotate("text", x = 4, y = 25, label = stringr::str_wrap(my_label, 5))

I don't think either of those will break up a single word, though, if that's what you're looking for.

Use a Unicode zero-width space and substitute all the _'s with _ + it:

library(stringi)
library(ggplot2)

my_label <- "Some_arbitrarily_larger_text"
my_label <- stri_replace_all_fixed(my_label, "_", "_\U200B")

To the naked eye it's continuous:

my_label
## [1] "Some_​arbitrarily_​larger_​text"

But, programmatically, it's a word break/wrap opportunity:

wrapper <- function(x, ...) paste(stri_wrap(x, ...), collapse = "\n")

ggplot(mtcars, aes(x = wt, y = mpg)) + 
  geom_point() +
  annotate("text", x = 4, y = 25, label = wrapper(my_label, width = 5))

enter image description here

Related