diff --git a/functions.qmd b/functions.qmd index 0f71598..54c589d 100644 --- a/functions.qmd +++ b/functions.qmd @@ -617,17 +617,7 @@ lin_check <- function(df, x, y) { } ``` -```{r} -# https://twitter.com/sharoz/status/1574376332821204999 - -# Facetting is fiddly - have to use special vars syntax. -foo <- function(x) { - ggplot(mtcars) + - aes(x = mpg, y = disp) + - geom_point() + - facet_wrap(vars({{ x }})) -} -``` +Of course you might combine both dplyr and ggplot2: ```{r} sorted_bars <- function(df, var) { @@ -639,18 +629,25 @@ sorted_bars <- function(df, var) { diamonds |> sorted_bars(cut) ``` -Of course you might combine both dplyr and ggplot2: +Next we'll discuss two more complicated cases: facetting and automatic labelling. + +### Facetting + +Unfortunately facetting is a special challenge, mostly because it was implemented well before we understood what tidy evaluation was and how it should work. +And unlike `aes()`, it wasn't straightforward to backport to tidy evalution, so you have to use a different syntax to usual. +Instead of writing `~ x`, you write `vars(x)` and instead of `~ x + y` you write `vars(x, y)`. +The only advantage of this syntax is that `vars()` is data masking so you can embrace within it. ```{r} -bars <- function(df, condition, var) { - df |> - filter({{ condition }}) |> - ggplot(aes({{ var }})) + - geom_bar() + - scale_x_discrete(guide = guide_axis(angle = 45)) -} +# https://twitter.com/sharoz/status/1574376332821204999 -diamonds |> bars(cut == "Good", clarity) +# Facetting is fiddly - have to use special vars syntax. +foo <- function(x) { + ggplot(mtcars) + + aes(x = mpg, y = disp) + + geom_point() + + facet_wrap(vars({{ x }})) +} ``` I've written these functions so that you can supply any data frame, but there are also advantages to hardcoding a data frame, if you're using it repeatedly: @@ -668,6 +665,20 @@ density(species) density(island, sex) ``` +Also note that I hardcoded the `x` variable but allowed the fill to vary. + +```{r} +bars <- function(df, condition, var) { + df |> + filter({{ condition }}) |> + ggplot(aes({{ var }})) + + geom_bar() + + scale_x_discrete(guide = guide_axis(angle = 45)) +} + +diamonds |> bars(cut == "Good", clarity) +``` + ### Labelling It'd be nice to label this plot automatically.