Easy geom recipes is open for comment. Please feel free to be in touch about issues (report an issue/edit this page/email/discuss). Recipe #1 is close to final form, and I will use that as a model - incorporating your feedback.
Welcome to ‘Easy geom recipes’ Recipe #3: creating geom_fitted and geom_residuals.
Creating a new geom_*() or stat_*() function is often motivated when plotting would require pre-computation otherwise. By using Stat extension, you can define computation to be performed within the plotting pipeline, as in the code that follows:
Example recipe #3: geom_fitted()
Step 0: use base ggplot2 to get the job done
It’s a good idea to look at how you’d get things done without Stat extension first, just using ‘base’ ggplot2. The computational moves you make here can serve a reference for building our extension function.
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr 1.1.4 ✔ readr 2.1.5
✔ forcats 1.0.0 ✔ stringr 1.5.1
✔ ggplot2 3.5.2 ✔ tibble 3.2.1
✔ lubridate 1.9.4 ✔ tidyr 1.3.1
✔ purrr 1.0.4
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag() masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
Now you are ready to begin building your extension function. The first step is to define the compute that should be done under-the-hood when your function is used. We’ll define this in a function called compute_group_lm_fitted(). The data input will look similar to the plot data. You will also need to include a scales argument, which ggplot2 uses internally.
compute_group_lm_fitted <-function(data, scales){ model<-lm(formula = y ~ x, data = data) data %>%mutate(y = model$fitted.values)}
You may have noticed …
… that our function uses the scales argument. The scales argument is used internally in ggplot2. So while it won’t be used in your test, you do need it for defining and using the ggproto Stat object in the next step.
… that the compute function assumes that variables x and y are present in the data. These aesthetic variables names, relevant for building the plot, are generally not found in the raw data inputs for ggplots.
Test compute.
## Test compute. penguins |>rename(x = bill_depth_mm, y = bill_length_mm) |>compute_group_lm_fitted()
# A tibble: 333 × 8
species island y x flipper_length_mm body_mass_g sex year
<fct> <fct> <dbl> <dbl> <int> <int> <fct> <int>
1 Adelie Torgersen 43.0 18.7 181 3750 male 2007
2 Adelie Torgersen 43.8 17.4 186 3800 female 2007
3 Adelie Torgersen 43.5 18 195 3250 female 2007
4 Adelie Torgersen 42.6 19.3 193 3450 female 2007
5 Adelie Torgersen 41.8 20.6 190 3650 male 2007
6 Adelie Torgersen 43.6 17.8 181 3625 female 2007
7 Adelie Torgersen 42.4 19.6 195 4675 male 2007
8 Adelie Torgersen 43.7 17.6 182 3200 female 2007
9 Adelie Torgersen 41.4 21.2 191 3800 male 2007
10 Adelie Torgersen 41.5 21.1 198 4400 male 2007
# ℹ 323 more rows
You may have noticed …
… that we prepare the data to have columns with names x and y before testing compute_group_medians. Computation will fail if the names x and y are not present given our function definition. Internally in a plot, columns are renamed when mapping aesthetics, e.g. aes(x = bill_depth, y = bill_length).
Step 2: Define new Stat. Test.
Next, we use the ggplot2::ggproto function which allows you to define a new Stat object - which will let us do computation under the hood while building our plot.
… that the naming convention for the ggproto object is CamelCase. The new class should also be named the same, i.e. "StatLmFitted".
… that we inherit from the ‘Stat’ class. In fact, your ggproto object is a subclass and you aren’t fully defining it. You simplify the definition by inheriting class properties from ggplot2::Stat. We have a quick look at defaults of generic Stat below. The required_aes and compute_group elements are generic and in StatLmFitted, we update the definition.
names(ggplot2::Stat) # which elements exist in Stat
ggplot2::Stat$required_aes # generic some kind of NULL behaivor
character(0)
that the compute_group_lm_fitted function is used to define our Stat’s compute_group element. This means that data will be transformed by our compute definition – group-wise if groups are specified.
that setting required_aes to ‘x’ and ‘y’ makes sense given compute assumptions. The compute assumes data to be a dataframe with columns x and y. If you data doesn’t have x and y, your compute will fail. Specifying required_aes in your Stat can improve your user interface because standard ggplot2 error messages will issue if required aes are not specified when plotting, e.g. ‘stat_medians() requires the following missing aesthetics: x.’
Test Stat.
You can test out your Stat using them in ggplot2 geom_*() functions.
that we don’t use “fitted” as the stat argument, which would be more consistent with base ggplot2 documentation. However, if you prefer, you can refer to your newly created Stat this way when testing, i.e. geom_point(stat = "fitted", size = 7).
Test group-wise behavior
last_plot() +aes(color = species)
Pro tip: Think about an early exit …
You might be thinking, what we’ve done would already be pretty useful to me. Can I just use my Stat as-is within geom_*() functions?
The short answer is ‘yes’! If you just want to use the Stat yourself locally in a script, there might not be much reason to go on to Step 3, user-facing functions. But if you have a wider audience in mind, i.e. internal to organization or open sourcing in a package, probably a more succinct expression of what functionality you deliver will be useful - i.e. write the user-facing functions.
Pro tip: consider using layer() function to test instead of geom_*(stat = StatNew)
Instead of using a geom_*() function, you might prefer to use the layer() function in your testing step. Occasionally, it’s necessary to go this route; for example, geom_vline() contain no stat argument, but you can use the GeomVline in layer(). If you are teaching this content, using layer() may help you better connect this step with the next, defining the user-facing functions.
A test of StatFitted using this method follows. You can see it is a little more verbose, as there is no default for the position argument, and setting the size must be handled with a little more care.
penguins |>ggplot() +aes(x = bill_depth_mm,y = bill_length_mm) +geom_point() +layer(geom = GeomPoint, stat = StatLmFitted, position ="identity", params =list(size =2)) +labs(title ="Testing StatLmFitted with layer() function")
Step 3: Define user-facing functions. Test.
In this next section, we define user-facing functions. Doing so is a bit of a mouthful, but see the ‘Pro tip: Use stat_identity definition as a template in this step …’ that follows.
stat_lm_fitted <-function(mapping =NULL, data =NULL, geom ="point", position ="identity", ..., show.legend =NA, inherit.aes =TRUE) {layer(data = data, mapping = mapping, stat = StatLmFitted, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params =list(na.rm =FALSE, ...))}
You may have noticed…
… that the stat_*() function name derives from the Stat objects’s name, but is snake case. So if I wanted a StatBigCircle based stat_*() function, I’d create stat_big_circle().
… that StatIndex is used to define the new layer function, so the computation that defines it, which is to summarize to medians, will be in play before the layer is rendered.
… that "label" is specified as the default for the geom argument in the function. This means that the ggplot2::GeomLabel will be used in the layer unless otherwise specified by the user.
Pro tip. Use stat_identity definition as a template in this step …
…
You may be thinking, defining a new stat_*() function is a mouthful that’s probably hard to reproduce from memory. So you might use stat_identity()’s definition as scaffolding to write your own layer. i.e:
Type stat_identity in your console to print function contents; copy-paste the function definition.
Switch out StatIdentity with your Stat, e.g. StatLmFitted.
Switch out "point" other geom (‘rect’, ‘text’, ‘line’ etc) if needed
Final touch, list2 will error without export from rlang, so update to rlang::list2.
Because users are more accustom to using layers that have the ‘geom’ prefix, you might also define geom with identical properties via aliasing.
geom_lm_fitted <- stat_lm_fitted
Be aware …
… verbatim aliasing as shown above is a bit of a shortcut and assumes that users will use the ‘geom_*()’ function with the stat-geom combination as-is. (For a discussion, see Constructors in ‘Extending ggplot2: A case Study’ in ggplot2: Elegant Graphics for Data Analysis. This section notes, ‘Most ggplot2 users are accustomed to adding geoms, not stats, when building up a plot.’)
An approach that is more consistent with existing guidance would be to hardcode the Geom and allow the user to change the Stat as follows.
# user-facing functiongeom_lm_fitted <-function(mapping =NULL, data =NULL, stat ="lm_fitted", position ="identity", ..., show.legend =NA, inherit.aes =TRUE) {layer(data = data, mapping = mapping, stat = stat, geom = GeomPoint, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = rlang::list2(na.rm =FALSE, ...))}
However, because it is unexpected to use geom_lm_fitted() with a Stat other than StatLmFitted (doing so would remove the fitted-ness) we think that the verbatim aliasing is a reasonable, time and code saving getting-started approach.
Here is a quick review of the functions and ggproto objects we’ve covered, dropping tests and discussion.
Review
library(tidyverse)# Step 1. Define computecompute_group_lm_fitted <-function(data, scales){ model <-lm(formula = y ~ x, data = data) data %>%mutate(y = model$fitted.values)}# Step 2. Define StatStatLmFitted =ggproto(`_class`="StatLmFitted",`_inherit`= Stat,required_aes =c("x", "y"),compute_group = compute_group_lm_fitted)# Step 3. Define user-facing functions## define stat_*()stat_lm_fitted <-function(mapping =NULL, data =NULL, geom ="point", position ="identity", ..., show.legend =NA, inherit.aes =TRUE) {layer(data = data, mapping = mapping, stat = StatLmFitted, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = rlang::list2(na.rm =FALSE, ...))}## define geom_*()geom_lm_fitted <- stat_lm_fitted
Your Turn: Write geom_residuals()
Using the geom_lm_fitted Recipe #3 as a reference, try to create a stat_lm_residuals() and convenience geom_fitted() that draws a segment between observed and fitted values for a linear model.
Hint: consider what aesthetics are required for segments. We’ll give you Step 0 this time…
Step 0: use base ggplot2 to get the job done
Step 1: Write compute function. Test.
Step 2: Write Stat.
Step 3: Write user-facing functions.
Congratulations!
If you’ve finished all three recipes, you feel for how Stats can help you build layer functions like stat_residuals and geom_residuals.