13
votes

I have a plot made with ggplot2 and I'd like to get the legend positioned in the top left corner.

legend.position = "top" gets me a legend positioned above the plot, but centered:

Legend is on top, but centered

legend.position = c(0,1) gets the legend in the top left, but it floats over the other plot elements:

Look at that legend float!

Know how to get that legend up in the top left without having it float? I tried declaring the legend height, but no dice. Do I have to adjust the size and position of the title and plot area?

Thanks!

2
You can further refine the position with legend.justification=c(1,1) - for example, p + theme(legend.position=c(1,1), legend.justification=c(1,1)). Since this will still be plotting in the graphics area, you may also want to play around with legend.background=element_blank() and legend.key=element.blank().JasonAizkalns
Thanks, I mistyped in the original question (it's since been edited). I meant top left, sorry! legend.justification is helpful in positioning the legend just right, but it floats over the graphics area. I'd like to get the legend out of the graphics area, like legend.position = "top" does so nicely.Conor Gaffney

2 Answers

23
votes

It can be done with legend.justification using predefined options.

library(ggplot2)

ggplot(mtcars, aes(x=factor(cyl), y=mpg, fill=factor(cyl))) + 
  geom_boxplot() +
  ggtitle("No title needed") +
  theme(legend.position='top', 
        legend.justification='left',
        legend.direction='horizontal')

enter image description here

17
votes

How about something like this -- not sure if there's a way to avoid the "hack" of \n\n\n in the call to ggtitle()

library(ggplot2)

ggplot(mtcars, aes(x = factor(cyl), y = mpg, fill = factor(cyl))) + 
  geom_boxplot() +
  ggtitle("A Title for Plot\n\n\n") +
  theme(
           legend.position = c(0, 1), 
      legend.justification = c(0, 0),
          legend.direction = "horizontal"
  )

Plot with Left-Justified Title Above Plot