Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap legend text in ggplot2

Tags:

r

ggplot2

Whilst producing graphs using ggplot2, I have some long legend names which I wish to wrap over two lines. For example:

a <- (1:10) b <- c(1,1.5,2,4,5,5.3,7,9,9.5,9.8) places = c("Birmingham","Chester-le-street","Cambridge", "Newcastle-upon-Tyne","Peterborough","Cambridge", "Newcastle-upon-Tyne","Peterborough","Liverpool","Stratford-upon-Avon") df1 = data.frame(a,b,places) library(ggplot2) i = ggplot(df1, aes(x=a, y=b)) + geom_point(aes(colour = places), size=3) + opts(legend.position="bottom") 

How would I go about wrapping the legend items when the box is set to be at the bottom - say in 2 or 3 lines? At the moment the seven items of the legend are next to each other. I would prefer that they are displayed in two rows (with say four towns on the top row and three towns on the second row).

Many thanks in advance.

like image 489
KT_1 Avatar asked Apr 26 '12 11:04

KT_1


1 Answers

Ok, given your edits, you probably wanted this:

library(scales) i + guides(colour = guide_legend(nrow = 2)) 

But you may find that you still want to employ the text wrapping technique as well, to get it to fit.

like image 179
joran Avatar answered Oct 06 '22 13:10

joran