简体   繁体   中英

Placing a color legend below a fill legend in ggplot

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

在此处输入图片说明

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")

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")

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM