Eliminating NAs from a ggplot
Solution 1:
You can use the function subset
inside ggplot2
. Try this
library(ggplot2)
data("iris")
iris$Sepal.Length[5:10] <- NA # create some NAs for this example
ggplot(data=subset(iris, !is.na(Sepal.Length)), aes(x=Sepal.Length)) +
geom_bar(stat="bin")
Solution 2:
Just an update to the answer of @rafa.pereira.
Since ggplot2
is part of tidyverse
, it makes sense to use the convenient tidyverse functions to get rid of NAs.
library(tidyverse)
airquality %>%
drop_na(Ozone) %>%
ggplot(aes(x = Ozone))+
geom_bar(stat="bin")
Note that you can also use drop_na()
without columns specification; then all the rows with NAs in any column will be removed.