ggplot: remove NA factor level in legend

后端 未结 3 513
说谎
说谎 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:36

    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)
    

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

    This works in ggplot2 3.1.0.

提交回复
热议问题