ggplot: remove NA factor level in legend

后端 未结 3 535
说谎
说谎 2020-12-31 03:13

How can I omit the NA level of a factor from a legend?

From the nycflights13 database, I created a new continuous variable called

3条回答
  •  佛祖请我去吃肉
    2020-12-31 03:38

    You have one data point where delay_class is NA, but tot_delay isn't. This point is not being caught by your filter. Changing your code to:

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

    does the trick:

    Alternatively, if you absolutely must have that extra point, you can override the fill legend as follows:

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

    UPDATE: As pointed out in @gatsky's answer, all discrete scales also include the na.translate argument. The feature actually existed since ggplot 2.2.0; I just wasn't aware of it at the time I posted my answer. For completeness, its usage in the original question would look like

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

提交回复
热议问题