Skip to Content
Intermediate Data Visualization in R

Facets allow us to visualize multiple discrete variables in one plot, showing each value of the facet variable in a different section.

The plot below shows our familiar hours slept by diet plot, this time with the addition of a third variable describing the taxonomic order of animals in our data. We see that rodents of all three diet types sleep much more than primates!

Facets: Mean Hours Asleep by Diet and Order

We can add facets to our plot by adding a facet_grid() layer and specifying the variables it maps to. To show values of a facet variable as rows, we specify facet_grid(rows = vars(row.var)). To show values of a facet variable as columns, we specify facet_grid(columns = vars(col.var)). We can also show two facet variables in a grid, e.g. facet_grid(rows = vars(row.var), columns = vars(col.var)).

The code below produces the plot shown at the beginning of this exercise. First, we process our data frame to include the records we want and calculate mean hours asleep. Next, we create our sleep by diet plot, this time mapping the order variable to a facet_grid() layer split into columns.

msleep_facets_df <- msleep %>% filter(status == "asleep") %>% na.omit() %>% group_by(diet, order) %>% summarize(mean.hours = mean(hours)) %>% filter(order %in% c("Primates", "Rodentia")) msleep_facet <- ggplot(msleep_facets_df, aes(x = diet, y = mean.hours)) + geom_bar(stat = "identity") + labs(title = "Mean Hours Asleep by Diet") + scale_x_discrete( limits = c("omni", "carni", "herbi"), labels = c("carni" = "Carnivore", "herbi" = "Herbivore", "omni" = "Omnivore")) + facet_grid(cols = vars(order))



Recall the clustered bar plot we created in Exercise 6, showing the percentage of students graduating by English proficiency, by year. For this exercise, we’ll compare the graduation rates across two high schools. Complete the code provided, adding a facet_grid() layer to display outcomes by School.ID. Represent levels of this variable as rows.

Print the plot to see what it looks like.

Folder Icon

Sign up to start coding

Already have an account?