简体   繁体   中英

How do I add a variable to the legend without including it in the graph?

I would like to add a value to the legend without adding it to the plot.

library(tidyverse)

gear_color <- c('black', "blue", "orange")
names(gear_color) <- c('3', '4', '5')

mtcars %>% 
  mutate(gear = factor(gear),
         vs = factor(vs)) %>% 
  filter(gear != 4) %>% 
  ggplot(aes(vs, fill = gear)) +
  geom_bar() +
  facet_wrap(~gear) +
  scale_fill_manual(values = gear_color)

add_to_ggplot_legend

How would I add Gear 4 to the legend without adding it to the plot?

The scale_fill_manual can take drop as parameter ( ?scale_fill_manual )

The ... - arguments passed onto discrete_scale

drop - Should unused factor levels be omitted from the scale? The default, TRUE, uses the levels that appear in the data; FALSE uses all the levels in the factor.

So, we can add drop = FALSE in the last line

... +
    scale_fill_manual(values = gear_color, drop = FALSE)

As @eipi10 mentioned in the comments, an empty facet for gear = 4 can be added similarly by include drop = FALSE in facet_wrap

-output

在此输入图像描述

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