Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wrapping legend text to fit the plot window

Tags:

r

ggplot2

I am using ggplot to chart some data and I noticed that legends text are very long and not fitting the window.

+ opts(legend.position = 'bottom', legend.direction = 'horizontal', size=0.1)  +
    guides(colour = guide_legend(nrow = 3), size=1) 

Is there an option in ggplot to wrap the legend text to fit the window.

like image 937
user1471980 Avatar asked Aug 23 '12 14:08

user1471980


Video Answer


1 Answers

Not as far as I know, so I have resorted to a workaround using strwidth(), which calculates the width of text in base graphics.

title <- "This is a really excessively wide title for a plot, especially since it probably won't fit"

Use par("din") to get the width of the device, and strwidth() to calculate the text size:

par("din")[1]
[1] 8.819444
strwidth(title, units="inches")
[1] 11.47222

Use it in a function and plot:

wrapTitle <- function(x, width=par("din")[1]){
  xx <- strwrap(x, width=0.8 * nchar(x) * width / strwidth(x, units="inches"))
  paste(xx, collapse="\n")
}

wrapTitle(title)
[1] "This is a really excessively wide title for a plot, especially since it\nprobably won't fit, meaning we somehow have to wrap it"

The plot:

ggplot(mtcars, aes(wt, mpg)) + geom_point() + opts(title=wrapTitle(title))

enter image description here


If you want to save the plot to file, then you can replace par("din") with the actual saved plot dimensions.

like image 140
Andrie Avatar answered Sep 21 '22 22:09

Andrie