1

I would like to add one title per row in the wrapped legend of the ggplot2 chart.

Something like this:

enter image description here

The code I'm using to generate this the legend:

library(ggplot2)
df <- data.frame(X=letters[1:6], Y=rnorm(6, mean=10, sd=1))
p <- ggplot(df, aes(x=X, y=Y, fill=X)) +
     geom_bar(stat="identity") +
     scale_fill_manual(
        values=c('#a6cee3','#1f78b4','#b2df8a','#33a02c','#A94774','#941751','#FFD479','#BEAD01'),
        name="",
        labels=c("1", "2", "3", "4", '5', '6', '7', '8'),
        guide=guide_legend(nrow=2, byrow=T, title='')
     ) +
     theme(legend.position='bottom')
p

Thanks!

alfakini
  • 4,635
  • 2
  • 26
  • 35
  • A [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) would be great (for the rest of the plot). Maybe using `mtcars` or `diamonds` or something? – mathematical.coffee Jul 24 '15 at 01:09
  • Thanks @mathematical.coffee, I just updated the question with a copy of your code without the solution so it make sense for people that are looking for the same answer. Thanks again for your answer :) – alfakini Jul 24 '15 at 14:33

1 Answers1

2

Add theme(legend.position='bottom') to move the legend to the bottom.

Use guide_legend(nrow=2, byrow=T, title='Row 1\nRow 2' to make your legend wrap to 2 lines and add "Row 1" on the top followed by "Row 2" underneath. However the lines are rather close together so if you add legend.title=element_text(lineheight=unit(1.5, 'lines')) to the theme that will space them better (sorry, I do not know if 1.5 is a value that will work all the time or whether you have to pick it manually, which is what I did).

Here's a (trivial) reproducible example (love the colours by the way - must earmark them for future use!):

library(ggplot2)
library(grid) # for `unit`
df <- data.frame(X=letters[1:6], Y=rnorm(6, mean=10, sd=1))
p <- ggplot(df, aes(x=X, y=Y, fill=X)) + geom_bar(stat="identity") +
       scale_fill_manual(
         values=c('#a6cee3','#1f78b4','#b2df8a','#33a02c','#A94774','#941751','#FFD479','#BEAD01'),
         name="",
         labels=c("1", "2", "3", "4", '5', '6', '7', '8'),
         guide=guide_legend(nrow=2, byrow=T, title='Row 1\nRow 2')
       ) +
       theme(
         legend.position='bottom',
         legend.title=element_text(lineheight=unit(1.5, 'lines'))
       )
p

enter image description here

mathematical.coffee
  • 55,977
  • 11
  • 154
  • 194