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