Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot: position legend in top left

Tags:

r

ggplot2

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!

like image 539
Conor Gaffney Avatar asked Mar 02 '15 18:03

Conor Gaffney


People also ask

How do I change the position of my legend in R?

position. 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 .

How do you move your position in legend?

For Moving the position of ggplot2 legend at any side of the plot, we simply add the theme() function to geom_point() function.

How do you make a legend outside the plot in R?

In order to draw our legend outside of the plotting area, we can use a combination of the “topright” argument and an additional specification of inset. The “topright” argument specifies that the legend should be in the upper right corner of the graph.

How do I change the legend text in ggplot2?

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


2 Answers

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

like image 119
ktyagi Avatar answered Sep 28 '22 11:09

ktyagi


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

like image 25
JasonAizkalns Avatar answered Sep 28 '22 09:09

JasonAizkalns