satyanarayan rao
satyanarayan rao

Reputation: 111

Wrap legend text containing expression

I have been looking for a wrapper function in ggplot2 which can help me put the legend text in a defined rectangular area.

So far I haven't found one. Here is my case:

library (ggplot2)
p = ggplot (mtcars, aes (x = mpg, y= cyl,color = factor (cyl)))
p + geom_point()
z = unique (factor (mtcars$cyl))
p + geom_point() + scale_color_manual(name="legend title", breaks = z, 
                                  labels = c (expression(a + b + c + d + e + f + g + h + i), expression(x) ,  expression(y ) ),
                                  values = c("red","blue","green") )

What I want is to have the long expression wrapped within a width of five characters.

Is there any function which can automatically wrap each legend key's text in a defined text width, and I am wondering if that can also be applicable for expressions.

Upvotes: 2

Views: 3308

Answers (1)

steveb
steveb

Reputation: 5532

The following, using str_wrap from stringr, should work for you. It wraps using a value of 5 as requested, but doesn't look that great.

library(ggplot2)
library(stringr)
p = ggplot (mtcars, aes (x = mpg, y= cyl,color = factor (cyl)))
p + geom_point()
z = unique (factor (mtcars$cyl))
p + geom_point() + scale_color_manual(name="legend title", breaks = z, 
                                      labels = c(str_wrap(expression(a + b + c + d + e + f + g + h + i), 5), expression(x) ,  expression(y ) ),
                                      values = c("red","blue","green") )

enter image description here

Upvotes: 3

Related Questions