KT_1
KT_1

Reputation: 8494

Wrap legend text in 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.

Upvotes: 39

Views: 43609

Answers (3)

User2321
User2321

Reputation: 3062

Another way to wrap the legend labels which I found very handy is the following (all credits to https://sites.google.com/site/simonthelwall/home/r/ggplot2#TOC-Wrapping-legend-labels):

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) 

i + scale_colour_discrete(labels = function(x) str_wrap(x, width = 5))

enter image description here

Upvotes: 17

joran
joran

Reputation: 173737

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.

Upvotes: 39

Etienne Low-D&#233;carie
Etienne Low-D&#233;carie

Reputation: 13443

From your example:

df1$places<-sub("-", "- \n ", df1$places)  

i = ggplot(df1, aes(x=a, y=b)) + geom_point(aes(colour = places), size=3)

enter image description here

Notes: - You can use gsub to replace all the "-" with "- \n "

Upvotes: 24

Related Questions