Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placing legend above main title

Tags:

r

legend

ggplot2

Placing the legend above the main title in ggplot2 when using theme(legend.position = "top") seemed to be the default (and unwanted) outcome in previous versions of ggplot: ggplot legend at top but below title?

In the current version of ggplot2, the legend places itself between the plot and the main title when setting theme(legend.position = "top"). A small example:

d <- data.frame(x = 1:2, y = 1:2, z = c("a", "b")) 
ggplot(d, aes(x = x, y = y, fill = z)) + 
  geom_col() +
  ggtitle("My title") +
  theme(legend.position = "top") 

enter image description here

How can I place the legend above main title?

like image 796
Reflexes Avatar asked Dec 04 '22 19:12

Reflexes


1 Answers

library(ggplot2)

ggplot(mtcars, aes(wt, mpg, color=cyl)) +
  geom_point() +
  labs(title = "Hey") +
  theme(plot.margin = margin(t=4,1,1,1, "lines")) +
  theme(legend.direction = "horizontal") +
  theme(legend.position = c(0.5, 1.2))

enter image description here

There are other ways as well, but this was the easiest one that came to mind.

like image 61
hrbrmstr Avatar answered Dec 11 '22 17:12

hrbrmstr