How can I place the legend title on top of the labels when the legend position is, for example, bottom?

Example:

xy <- data.frame(x=1:10, y=10:1, type = rep(LETTERS[1:2], each=5))

plot <- ggplot(data = xy)+
  geom_point(aes(x = x, y = y, color=type)) +
  theme(legend.position = 'bottom')

plot

How can we get the title 'type' on top of A and B, not to their left?

Thanks

Upvotes: 3

Views: 2699

Answers (1)

Eugen
Eugen

Reputation: 442

You can get rid of your problem using guides() and specifying title position.

library(ggplot2)
xy <- data.frame(x=1:10, y=10:1, type = rep(LETTERS[1:2], each=5))

plot <- ggplot(data = xy)+ geom_point(aes(x = x, y = y, color=type)) +
        theme(legend.position = 'bottom') + 
        guides(colour = guide_legend(title.position = "top"))

plot

Although this is old, I noticed that this answer Legend title position in ggplot2 is good yet, even if ggplot2 is now many versions above 0.9. I noticed that is not necessary anymore the call to library(scales). Hope this helps

Upvotes: 4

Related Questions