ggplot2 Inline Subsetting for categorical variables


Example

ggplot(iris[iris$Species == "setosa",],aes(Sepal.Width)) + 
    geom_density()

Here, we are subsetting the dataframe before passing it to ggplot. It is a very useful tool derived from the data frame data structure.

To make the code more readable, one can also use dplyr's filter:

library(dplyr)
iris %>% filter(Species == "setosa") %>% ggplot(aes(Sepal.Width)) + 
    geom_density()