Skip to content

Commit 25258f5

Browse files
authored
add facet examples (#5725)
1 parent 85bd22c commit 25258f5

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

vignettes/ggplot2-in-packages.Rmd

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,8 @@ To create any graphic using ggplot2 you will probably need to use `aes()` at lea
5858
```{r}
5959
mpg_drv_summary <- function() {
6060
ggplot(ggplot2::mpg) +
61-
geom_bar(aes(x = drv)) +
62-
coord_flip()
61+
geom_bar(aes(y = drv)) +
62+
facet_wrap(vars(year))
6363
}
6464
```
6565

@@ -81,33 +81,33 @@ If you already know the mapping in advance (like the above example) you should u
8181
```{r}
8282
mpg_drv_summary <- function() {
8383
ggplot(ggplot2::mpg) +
84-
geom_bar(aes(x = .data$drv)) +
85-
coord_flip()
84+
geom_bar(aes(y = .data$drv)) +
85+
facet_wrap(vars(.data$year))
8686
}
8787
```
8888

8989
If you have the column name as a character vector (e.g., `col = "drv"`), use `.data[[col]]`:
9090

9191
```{r}
92-
col_summary <- function(df, col) {
92+
col_summary <- function(df, col, by) {
9393
ggplot(df) +
94-
geom_bar(aes(x = .data[[col]])) +
95-
coord_flip()
94+
geom_bar(aes(y = .data[[col]])) +
95+
facet_wrap(vars(.data[[by]]))
9696
}
9797
98-
col_summary(mpg, "drv")
98+
col_summary(mpg, "drv", "year")
9999
```
100100

101101
If the column name or expression is supplied by the user, you can also pass it to `aes()` or `vars()` using `{{ col }}`. This tidy eval operator captures the expression supplied by the user and forwards it to another tidy eval-enabled function such as `aes()` or `vars()`.
102102

103103
```{r, eval = (packageVersion("rlang") >= "0.3.4.9003")}
104-
col_summary <- function(df, col) {
104+
col_summary <- function(df, col, by) {
105105
ggplot(df) +
106-
geom_bar(aes(x = {{ col }})) +
107-
coord_flip()
106+
geom_bar(aes(y = {{ col }})) +
107+
facet_wrap(vars({{ by }}))
108108
}
109109
110-
col_summary(mpg, drv)
110+
col_summary(mpg, drv, year)
111111
```
112112

113113
To summarise:

0 commit comments

Comments
 (0)