简体   繁体   English

ggplot 将变量添加到图例而不包括在绘图中(使用 alpha 时)

[英]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? )我认为当我不使用alpha时不会出现问题(请参阅: 如何将变量添加到图例而不将其包含在图表中?

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 .这个问题与alpha无关。 The problem is the class of your data.问题是您的数据的类别。 When you use tibble to create your data, the name column is of class character .当您使用tibble创建数据时, name列的类为character You need a factor class to "remember" the unused levels:您需要一个factor类来“记住”未使用的级别:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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