Facets
Creating multi-panel plots using facets
.
Problem
You want to see more aspects of your data, and it's not practical to use the regular aesthetics
approach for that.
Solution - facets
You can add one or more new dimensions to your plot using faceting
.
This approach allows you to split up your data by one or more variables and plot the subsets of data together.
In this demo, we will explore how various faceting functions work, as well as the built-in sorting
and formatting
options.
To learn more about formatting templates, see: Formatting.
miles per gallon | number of cylinders | engine displacement \(cu. inches\) | engine horsepower | vehicle weight \(lbs.\) | time to accelerate \(sec.\) | model year | origin of car | vehicle name |
---|---|---|---|---|---|---|---|---|
18 | 8 | 307 | 130 | 3504 | 12 | 70 | US | chevrolet chevelle malibu |
15 | 8 | 350 | 165 | 3693 | 11.5 | 70 | US | buick skylark 320 |
18 | 8 | 318 | 150 | 3436 | 11 | 70 | US | plymouth satellite |
One plot
Create a scatter plot to show how mpg
is related to a car's engine horsepower
.
Also use the color
aesthetic to visualize the region where a car was designed.
More dimensions
There are two functions for faceting:
facetGrid()
facetWrap()
The former creates 2-D matrix of plot panels, and the latter creates 1-D strip of plot panels.
We'll be using the number of cylinders
variable as the first faceting variable, and sometimes the origin of car
as a second faceting variable.
facetGrid()
The data can be split up by one or two variables that vary in the X and/or Y direction.
One facet
Let's split up the data by number of cylinders
.
Two facets
Split up the data by two faceting variables: number of cylinders
and origin of car
.
Formatting and sorting.
Apply a formatting template to the number of cylinders
and sort the origin of car
values in descending order.
To learn more about formatting templates, see: Formatting.
facetWrap()
The data can be split up by one or more variables. The panel layout is flexible and controlled by ncol
, nrow
and dir
options.
Facet Wrap One Column
Split data by the number of cylinders
variable and arrange tiles in two rows.
Facet Wrap Two Columns
Split data by origin of car
and number of cylinders
and arrange tiles in five columns.
Arrange panels vertically.
Use the dir
parameter to arrange tiles by columns, in three columns (the default tile arrangement is "by row").
Also, format number of cylinders
labels and reverse the sorting direction for this faceting variable.
Free scales on faceted plot
Faceted plot
facetGrid()
with fixed
scales (the default)
Scales are constant across all panels.
facetGrid()
with free
Y-scales
facetWrap()
with fixed
scales (the default)
Scales are constant across all panels.