Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Legend title position in ggplot2

Anone know how to change the position of the legend title in ggplot?

I have used the following code to move the legend to the bottom and make it horizontal

p <- p + opts(legend.position = 'bottom', legend.direction = 'horizontal')

But now I want the title to be to the left of the legend instead of above. I've looked in the follwing places but cant find it or figure it out:

https://github.com/hadley/ggplot2/wiki/Legend-Attributes http://had.co.nz/ggplot2/book/toolbox.r

Any assistance would be greatly appreciated

like image 981
MikeTP Avatar asked Mar 16 '12 15:03

MikeTP


People also ask

How do you set the position of a legend in R?

You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.

How do I change the legend title in ggplot2?

You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))

How do I change the order of my legend in ggplot2?

You can use the following syntax to change the order of the items in a ggplot2 legend: scale_fill_discrete(breaks=c('item4', 'item2', 'item1', 'item3', ...)


1 Answers

Using the transition guide to version 0.9 as a reference, you might try the following (assuming you want to change the title position for the colour legend):

library(scales)
+ guides(colour = guide_legend(title.position = "left"))

For a continuous scale you'd use guide_colorbar instead of guide_legend.

Just to provide a concrete example to prove I'm not just making this up,

library(ggplot2)
library(scales)
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point(aes(colour = qsec)) + 
    guides(colour = guide_legend(title.position = "right"))

enter image description here

like image 114
joran Avatar answered Oct 03 '22 04:10

joran