parent
e0f692a705
commit
5aac0e9d75
|
@ -396,9 +396,11 @@ One way to add additional variables to a plot is by mapping them to an aesthetic
|
||||||
Another way, which is particularly useful for categorical variables, is to split your plot into **facets**, subplots that each display one subset of the data.
|
Another way, which is particularly useful for categorical variables, is to split your plot into **facets**, subplots that each display one subset of the data.
|
||||||
|
|
||||||
To facet your plot by a single variable, use `facet_wrap()`.
|
To facet your plot by a single variable, use `facet_wrap()`.
|
||||||
The first argument of `facet_wrap()` is a formula, which you create with `~` followed by a variable name (here, "formula" is the bane if a data structure in R, not a synonym for "equation").
|
The first argument of `facet_wrap()` is a formula[^data-visualize-1], which you create with `~` followed by a variable name.
|
||||||
The variable that you pass to `facet_wrap()` should be discrete.
|
The variable that you pass to `facet_wrap()` should be discrete.
|
||||||
|
|
||||||
|
[^data-visualize-1]: Here "formula" is the name of the type of thing created by `~`, not a synonym for "equation".
|
||||||
|
|
||||||
```{r}
|
```{r}
|
||||||
#| fig-alt: >
|
#| fig-alt: >
|
||||||
#| Scatterplot of highway fuel efficiency versus engine size of cars,
|
#| Scatterplot of highway fuel efficiency versus engine size of cars,
|
||||||
|
@ -409,9 +411,8 @@ ggplot(data = mpg) +
|
||||||
facet_wrap(~cyl)
|
facet_wrap(~cyl)
|
||||||
```
|
```
|
||||||
|
|
||||||
To facet your plot on the combination of two variables, add `facet_grid()` to your plot call.
|
To facet your plot with the combination of two variables, switch from `facet_wrap()` to `facet_grid()`.
|
||||||
The first argument of `facet_grid()` is also a formula.
|
The first argument of `facet_grid()` is also a formula, but now it's a double sided formula: `rows ~ cols`.
|
||||||
This time the formula should contain two variable names separated by a `~`.
|
|
||||||
|
|
||||||
```{r}
|
```{r}
|
||||||
#| fig-alt: >
|
#| fig-alt: >
|
||||||
|
@ -426,8 +427,6 @@ ggplot(data = mpg) +
|
||||||
facet_grid(drv ~ cyl)
|
facet_grid(drv ~ cyl)
|
||||||
```
|
```
|
||||||
|
|
||||||
If you prefer to not facet in the rows or columns dimension, use a `.` instead of a variable name, e.g. `+ facet_grid(. ~ cyl)`.
|
|
||||||
|
|
||||||
### Exercises
|
### Exercises
|
||||||
|
|
||||||
1. What happens if you facet on a continuous variable?
|
1. What happens if you facet on a continuous variable?
|
||||||
|
|
Loading…
Reference in New Issue