Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wrapping long geom_text labels

Tags:

r

ggplot2

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!

like image 713
Alexander Avatar asked Nov 23 '17 01:11

Alexander


1 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.

like image 132
edavidaja Avatar answered Oct 28 '22 20:10

edavidaja