简体   繁体   中英

ggplot add variable to legend without including in plot (when using alpha)

I want to add a variable to the legend without including it in the plot.

I think problem doesn't occur when I don't use alpha (see: How do I add a variable to the legend without including it in the graph? )

library(tidyverse)

name_color <- c('black', "blue", "orange", "pink")
names(name_color) <- letters[1:4]

tibble(name = rep(letters[1:4], each = 2),
       respond = rep(c("yes", "no"), 4),
       n = rep(50, 8),
       me = "i") %>%
  filter(name != "c") %>% 
  ggplot(aes(me, n, fill = name, alpha = respond)) +
  facet_wrap(~name) +
  geom_bar(stat = "identity") +
  scale_fill_manual(values = name_color, drop = FALSE)

add_to_legend

The issue has nothing to do with alpha . The problem is the class of your data. When you use tibble to create your data, the name column is of class character . You need a factor class to "remember" the unused levels:

name_color <- c('black', "blue", "orange", "pink")
names(name_color) <- letters[1:4]
d = tibble(name = rep(letters[1:4], each = 2),
       respond = rep(c("yes", "no"), 4),
       n = rep(50, 8),
       me = "i") %>%

class(d$name)
# [1] "character"

d %>% mutate(name = factor(name)) %>%  
  filter(name != "c") %>% 
  ggplot(aes(me, n, fill = name, alpha = respond)) +
  facet_wrap(~name) +
  geom_bar(stat = "identity") +
  scale_fill_manual(values = name_color, drop = FALSE)

在此处输入图片说明

In the original question you link, you had the factor conversion explicitly, which is why it worked.

... %>% mutate(
  gear = factor(gear),
  vs = factor(vs)
) %>% ...

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