1

If I have the following plot, how would I place the color (error) legend item below the fill (yr) one?

enter image description here

library(dplyr)
library(ggplot2)

dat <- data.frame(yr = c(2017:2019) %>% as.factor,
                  val = 1:3)

dat %>% 
  ggplot(aes(x = yr, y = val, fill = yr)) +
  geom_bar(stat = "identity") +
  geom_errorbar(aes(ymin = 7, ymax = 7,
                    color = "Error")) +
  theme(legend.position = "bottom")
DJC
  • 1,491
  • 6
  • 19

1 Answers1

2

There are two parts, you need to change the order with guides and then add legend.box = "vertical" to theme:

dat %>% 
  ggplot(aes(x = yr, y = val, fill = yr)) +
  geom_bar(stat = "identity") +
  geom_errorbar(aes(ymin = 7, ymax = 7,
                    color = "Error")) +
  guides(fill = guide_legend(order = 1),
         color = guide_legend(order = 2)) +
  theme(legend.box="vertical", legend.position = "bottom")

enter image description here

Ian Campbell
  • 23,484
  • 14
  • 36
  • 57