43

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

Pesky NA legend value.....

From the nycflights13 database, I created a new continuous variable called tot_delay, and then created a factor called delay_class with 4 levels. When I plot, I filter out NA values, but they still appear in the legend. Here's my code:

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

4 Answers 4

73

The parent example isn't a good illustration of the problem (of course unexpected NA values should be tracked down and eliminated), but this is the top result on Google so it should be noted that there is a now an option in scale_XXX_XXX to prevent NA levels from displaying in the legend by setting na.translate = F. For example:

# 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

This works in ggplot2 3.1.0.

36

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:

enter image description here

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)
1
  • 1
    Ah! So simple. I should have filtered by delay_class to begin with. Since there was one extra point, it was difficult to see that NA on the graph itself, although it showed on the legend. You have my vote for the scale_fill_manual() method of overwriting a legend. Commented Aug 3, 2017 at 20:15
4

You could also use scale_color_manual or scale_fill_manual when knowing that the color of NA is grey50. So you could specify the values and only the breaks for the ones you want to plot. Here is some reproducible code (data @gatsky):

df = data.frame(x = c(1,2,NA), y = c(1,1,NA), a = c("A","B",NA))
library(ggplot2)
ggplot(data = df, aes(x, y, colour = a)) + 
  geom_point(size = 4) +
  scale_color_manual(values = c("red", "blue", "grey50"),
                     breaks = c("A", "B"))

As you can see by specifying all the colors in values and only the breaks for A and B will remove the NA from the legend.


If you want to have the standard colors in your legend, you could use the hue_pal function from the scales package like this:

df = data.frame(x = c(1,2,NA), y = c(1,1,NA), a = c("A","B",NA))
library(ggplot2)
library(scales)
ggplot(data = df, aes(x, y, colour = a)) + 
  geom_point(size = 4) +
  scale_color_manual(values = c(hue_pal()(2), "grey50"),
                     breaks = c("A", "B"))


And finally using the data from the OP with an scale_fill_manual example like this:

library(nycflights13) 
library(ggplot2)
library(dplyr)
library(scales)

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

Created on 2023-03-25 with reprex v2.0.2

1

I like @Artem's method above, i.e., getting to the bottom of why there are NA's in your df. However, sometimes you know there are NA's, and you just want to exclude them. In that case, simply using 'na.omit' should work:

na.omit(flights) %>% ggplot() +
geom_bar(mapping = aes(x = carrier, fill = delay_class), position = "fill")
3
  • 3
    The problem with this, is that it removes all rows with NA values in any column, not just the column I'm filling with ggplot. This may lead to some observations filtered out that one would want to keep in. Commented Jul 12, 2018 at 0:42
  • 1
    @RichPauloo -- you question, quoted from above, was "How can I easily omit NA values from the legend?" If you had difficulty (for whatever reason) finding which variable or variables it was that was giving you the problem, then using 'na.omit' would be expedient. However, I always encourage people to figure out why they have NA's, as mentioned in my reply. So, here is a question for you (since I checked my code before posting). What is the difference in the file / cases / rows in the flights file if you use 'na.omit(flights)' vs. 'filter(flights, !is.na(tot_delay))' ?
    – Woodstock
    Commented Jul 18, 2018 at 18:05
  • The difference is that if you'd use different dataset, you could unexpectedly lose data using na.omit(). The dplyr approach is more robust.
    – WojciechF
    Commented Aug 9, 2019 at 7:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.