Rotate boxplot legend (R, ggplot2)

Viewed 837

I am using the following code.

 library(ggplot2)
 mtcars$carb <- as.factor(mtcars$carb)
 mtcars$am <- as.factor(mtcars$am)
 mtcars <- mtcars[!(mtcars$carb==6 | mtcars$carb==8),]
 ggplot(mtcars) + 
    geom_boxplot(aes(x = carb, y = mpg, fill = am), 
                 position = position_dodge(0.9)) +
 guides(fill = guide_legend(direction = "horizontal"))

This results in:

enter image description here

I would like to rotate the legend to obtain this desired result:

enter image description here

Might anyone please help? Thank you.

2 Answers

Okay, I figured it out following a suggestion by @LFischer. There is probably an easier way, but after some trial and error, this did it for me:

 library(ggplot2)
 mtcars$carb <- as.factor(mtcars$carb)
 mtcars$am <- as.factor(mtcars$am)
 mtcars <- mtcars[!(mtcars$carb==6 | mtcars$carb==8),]
 ggplot(mtcars) + 
    geom_boxplot(aes(x = carb, y = mpg, fill = am), 
                 position = position_dodge(0.9)) +
 guides(fill = guide_legend(reverse = TRUE, direction = "vertical", label.position = "top", label.theme = element_text(angle = 90, vjust = 0.5), title.position = "bottom", title.theme = element_text(angle = 90)))

You can just put it on the top

library(ggplot2)
 mtcars$carb <- as.factor(mtcars$carb)
 mtcars$am <- as.factor(mtcars$am)
 mtcars <- mtcars[!(mtcars$carb==6 | mtcars$carb==8),]
 ggplot(mtcars) + 
    geom_boxplot(aes(x = carb, y = mpg, fill = am), 
                 position = position_dodge(0.9)) +
theme(legend.position = "top")

example_img

Or you can make it vertical

library(ggplot2)
mtcars$carb <- as.factor(mtcars$carb)
mtcars$am <- as.factor(mtcars$am)
mtcars <- mtcars[!(mtcars$carb==6 | mtcars$carb==8),]
ggplot(mtcars) + 
  geom_boxplot(aes(x = carb, y = mpg, fill = am), 
               position = position_dodge(0.9)) +
  theme(legend.direction = "vertical")

example_img_2

Hope it helps

Related