Search code examples
rggplot2forcats

Do not plot some counts with ggplot2


As a reproducible example, use

library(tidyverse)
iris_count <- count(iris, Species)

iris_count %>%
  mutate(Species2 = ifelse(Species == "setosa", NA, as.character(Species))) %>%
  ggplot(aes(reorder(Species2, -n), n)) +
  geom_col(na.rm = TRUE)

I want to remove the NA from the plot, but option na.rm = TRUE doesn't seem to do what I want in this case.


Solution

  • Use scale_x_discrete and argument na.translate = FALSE. From scale_x_discrete documentation :

    na.translate Unlike continuous scales, discrete scales can easily show missing values, and do so by default. If you want to remove missing values from a discrete scale, specify na.translate = FALSE.

    library(ggplot2)
    library(dplyr)
    iris_count <- count(iris, Species)
    
    iris_count %>%
      mutate(Species2 = ifelse(Species == "setosa", NA, as.character(Species))) %>%
      ggplot(aes(reorder(Species2, -n), n)) +
      geom_col() + 
      scale_x_discrete(na.translate = FALSE)