Get startedGet started for free

Facet wrap & margins

1. Facet wrap & margins

In the last video we explored facet_grid() for splitting up a plot according to a categorical variable.

2. Adjusting the plotting space

We saw that this allowed us to set a free x axis for all plots the same column and a free y axis for all plots in the same row. That's alright, but wouldn't it be great if each plot can also have it's own x and y axes dependent on their data? Actually, it kind of defeats the purpose of having small multiples, but it can be useful if we have distinct ranges. To achieve this, we can take advantage of another useful function in this layer: facet_wrap

3. Using facet_wrap()

There are a couple use cases for this function. First, as I just mentioned, when we want each plot to have its own plotting space, but we still want to take advantage of tidy data structure and ggplot2 to generate all those plots as facets of a larger plot, and not as individual plots.

4. Using facet_wrap() - Scenario 1

For facet_wrap, we specify one or more faceting variables with a single call to the vars function. facet_wrap will automatically choose an appropriate number of columns and rows. So this gets the job done, but you can see that it is more difficult to keep track of each plot and variable compared to facet_grid, so use this with caution.

5. Using facet_wrap()

Second, and what is a more typical scenario, is when our categorical variable has many groups, so that faceting along only rows or only columns is overwhelming.

6. Using facet_wrap() - Scenario 2

For example, here, our 51 animals belong to 13 taxonomic orders which is nicely displayed with facet wrap. Using facet grid would produce a single row or column with 13 plots, which would be impractical.

7. Using margin plots

Before we wrap up with facets, let's look at one more adjustment we can make with this layer. We can present each facet _and_ a composite plot with all categories together. These are called margin plots. This was our original facetted plot, but

8. Using margin plots

if we add the margins argument to the facet layer, we can add margin plots for both the rows and columns that display all points together. Notice that in the lower right corner, we have the complete data set in one facet.

9. Using margin plots

We can also specify one one variable to produce the margin plots.

10. Let's practice!

So far so good. We've seen that there is a lot more to the facet layer than just splitting up your plots. Let's explore these last concepts in the exercises.