ggplot:删除图例中的NA因子级别

时间:2017-08-03 19:37:30

标签: r ggplot2

这是一个密谋问题。

在nycflights13数据库中,我创建了一个名为tot_delay的新连续变量,然后创建了一个名为delay_class的因子,包含4个级别。当我绘制时,我会过滤掉NA值,但它们仍会出现在图例中。

Pesky NA legend value.....

如何轻松省略图例中的NA值?这是我的代码:

library(nycflights13); library(ggplot2)

flights$tot_delay = flights$dep_delay + flights$arr_delay
flights$delay_class <- cut(flights$tot_delay,                                   
                           c(min(flights$tot_delay, na.rm = TRUE), 0, 20 , 120,
                             max(flights$tot_delay, na.rm = TRUE)),   
                           labels = c("none", "short","medium","long"))     

filter(flights, !is.na(tot_delay)) %>% 
  ggplot() +
  geom_bar(mapping = aes(x = carrier, fill = delay_class), position = "fill")

3 个答案:

答案 0 :(得分:12)

您有一个数据点delay_classNA,但tot_delay不是。您的过滤器未捕获此点。将代码更改为:

filter(flights, !is.na(delay_class)) %>% 
  ggplot() +
  geom_bar(mapping = aes(x = carrier, fill = delay_class), position = "fill")

诀窍:

enter image description here

或者,如果你绝对必须有这个额外的点,你可以覆盖fill图例,如下所示:

filter(flights, !is.na(tot_delay)) %>% 
  ggplot() +
  geom_bar(mapping = aes(x = carrier, fill = delay_class), position = "fill") +
  scale_fill_manual( breaks = c("none","short","medium","long"),
                    values = scales::hue_pal()(4) )

答案 1 :(得分:5)

父示例并不能很好地说明问题(当然,应该跟踪并消除意外的NA值),但这是Google上的最高结果,因此应注意现在是scale_XXX_XXX中的一个选项,可通过设置na.translate = F来防止NA水平显示在图例中。例如:

# default    
ggplot(data = data.frame(x = c(1,2,NA), y = c(1,1,NA), a = c("A","B",NA)),
           aes(x, y, colour = a)) + geom_point(size = 4)

enter image description here

# with na.translate = F    
ggplot(data = data.frame(x = c(1,2,NA), y = c(1,1,NA), a = c("A","B",NA)),
           aes(x, y, colour = a)) + geom_point(size = 4) + 
           scale_colour_discrete(na.translate = F)

enter image description here

这在ggplot2 3.1.0中有效。

答案 2 :(得分:3)

我喜欢@ Artem上面的方法,也就是说,为什么你的df中有NA的底部。但是,有时你知道有NA,你只想排除它们。在这种情况下,只需使用'na.omit'即可:

na.omit(flights) %>% ggplot() +
geom_bar(mapping = aes(x = carrier, fill = delay_class), position = "fill")