--- title: "Developing Pattern Geoms" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Developing Pattern Geoms} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, dev = "ragg_png", fig.width = 6, fig.height = 3.5, comment = "#>" ) has_hexbin <- requireNamespace("hexbin", quietly = TRUE) ``` ```{r setup} library("ggplot2") library("ggpattern") ``` ## Overview `{ggpattern}` provides a pattern version of most `{ggplot2}` geoms (e.g. `geom_rect_pattern()`). For any other geom (from `{ggplot2}` or an extension package) there are four ways to fill its areas with patterns, from the least to the most work: 1. `with_pattern()` makes a pattern layer from a layer, for a one-off plot. 2. `make_geom_pattern()` makes a `geom_*_pattern()` function from a `geom_*()` function, for reuse. 3. `make_GeomPattern()` makes a pattern geom from a geom, for a pattern `Geom` object of your own. 4. Writing the pattern geom's draw methods yourself with `with_pattern_aes()` and `with_pattern_key()`, for full control. All four draw the parent geom's grob as usual and then fill each of its areas with the pattern of its row of the layer's data using `gridpattern::with_pattern()`. Each area's fill, pattern, and border are drawn in turn (like `{ggplot2}` draws its areas) so overlapping areas stack as they would without patterns. To write a new *pattern* (rather than a new geom) see `vignette("developing-patterns", package = "ggpattern")`. ## `with_pattern()`: a pattern layer from a layer `with_pattern()` (re-exported from `{gridpattern}`) takes a layer and pattern aesthetics set to constants (in `...`) or mapped (in `mapping`): ```{r with-pattern, eval = requireNamespace("magick", quietly = TRUE)} ggplot(mtcars, aes(mpg, wt)) + geom_point() + with_pattern(geom_smooth(method = "lm", formula = y ~ x), pattern = "plasma", pattern_alpha = 0.7) ``` If `{ggpattern}` has a pattern geom for the layer's geom (e.g. `GeomRectPattern` for `geom_rect()`) it is used, otherwise the pattern geom is made by `make_GeomPattern()`. Only the layer's geom is replaced so it keeps its stat, position, and other parameters. ## `make_geom_pattern()`: a pattern geom function from a geom function `make_geom_pattern()` makes a `geom_*_pattern()` function from a `geom_*()` function: ```{r make-geom-pattern-function} geom_smooth_pattern <- make_geom_pattern(geom_smooth) ggplot(mtcars, aes(mpg, wt, colour = factor(am), pattern = factor(am))) + geom_point() + geom_smooth_pattern(method = "lm", formula = y ~ x, pattern_colour = "grey40", pattern_spacing = 0.03) ``` The function it returns calls the original function and then `with_pattern()` on the layer it returns so it keeps the original's stat, position, and every other default. Its arguments are `mapping` and `...`: the pattern aesthetics among them are held back for `with_pattern()` and the others are passed on to the original function. ## `make_GeomPattern()`: a pattern geom from a geom `make_GeomPattern()` makes a pattern `Geom` from a `Geom`: it has the geom's aesthetics plus the pattern aesthetics, draws the geom's grob with its areas filled with patterns, and draws the geom's legend key glyph filled with the key's pattern. Use `ggplot2::make_constructor()` to make its `geom_*_pattern()` function: ```{r make-geom-pattern, eval = requireNamespace("ggridges", quietly = TRUE)} GeomDensityRidgesPattern <- make_GeomPattern(ggridges::GeomDensityRidges) geom_density_ridges_pattern <- make_constructor(GeomDensityRidgesPattern, stat = ggridges::StatDensityRidges, position = ggridges::position_points_sina()) ggplot(iris, aes(Sepal.Length, Species, pattern = Species)) + geom_density_ridges_pattern(pattern_spacing = 0.03) ``` (`make_geom_pattern()` given the geom and the same `stat` and `position` does both steps but only returns the function.) A `Geom` doesn't know the default `stat` and `position` of its `geom_*()` function (they are arguments of that function) so pass them to `make_constructor()` if they aren't `"identity"`, as with the stat (which computes `height`) and position of `ggridges::geom_density_ridges()` above. Without the stat the layer may fail with an error about missing aesthetics the stat would have computed. (We give them as objects rather than as strings e.g. `stat = "density_ridges"` since a stat or position named by a string is only found if its package is attached.) Likewise a constructor argument's default is taken from the geom's draw method which may differ from what its `geom_*()` function passes to it: `GeomSmooth` only draws its confidence band (the area to fill) if `se = TRUE` which is the default of `geom_smooth()` but not of `GeomSmooth$draw_group()`, and in the development version of `{ggplot2}` `geom_smooth()` also hides the outline of the band which `GeomSmooth$draw_group()` draws by default. `make_geom_pattern()` given the `geom_*()` function avoids having to know any of these, so prefer it if there is a `geom_*()` function. ### Matching areas to rows: `area_by` The pattern geom needs to know which row of the data each area of the grob was drawn for. `area_by` says how: * `"row"`: the geom draws an area per row in row order (e.g. `GeomRect` and `GeomHex`). * `"group"`: the geom draws an area per group sorted by group (e.g. `GeomPolygon`) or its `draw_group()` method draws a single area (e.g. `GeomRibbon` and `GeomViolin`). * `"trace"`: the geom is drawn with a different `fill` per row and each area gets the pattern of the row whose `fill` it was drawn with (and then its actual `fill` back). This works for most geoms without knowing how they draw their areas (e.g. one that draws its areas in a different order than its rows) but it draws the geom twice and needs it to draw each area with its row's (character) `fill`. Areas not drawn with a row's `fill` (e.g. decorations) are left alone. * A function of the data frame returning the rows of the areas in drawing order (or a single row for every area). It is also given the draw method's other parameters (e.g. `lineend`) by name if it has an argument of that name (or `...`), since some geoms' drawing order depends on them. By default `make_GeomPattern()` uses what it knows the `{ggplot2}` geoms need and otherwise `"trace"`, so `area_by` is mainly for speed or for a geom that tracing can't handle. If the geom's grob doesn't have as many areas as `area_by` gives rows the error says which geom and `area_by` and suggests trying `area_by = "trace"`. A grob that only makes its areas when it is drawn (e.g. in a `makeContent()` method) is filled when it is drawn. ### Using `make_GeomPattern()` in a package Code at the top level of a package's `R/` files is run when the package is *installed*, not when it is loaded. So a pattern geom made there by `make_GeomPattern()` stores a copy of the geom it was made from (its methods, default aesthetics, and draw method arguments) as it was when your package was installed (for a binary package when it was built). If that geom is from another package (e.g. `{ggplot2}`) which is later updated without your package being reinstalled the pattern geom keeps using the old copy: it won't have any new aesthetics or parameters and its old methods may fail with the updated package. (This doesn't affect `with_pattern()` or `make_GeomPattern()` used in a script or within a function, nor a geom from your own package.) Either make the pattern geom (and its constructor) when your package is loaded: ```{r onload, eval = FALSE} GeomDensityRidgesPattern <- NULL geom_density_ridges_pattern <- NULL .onLoad <- function(libname, pkgname) { GeomDensityRidgesPattern <<- ggpattern::make_GeomPattern(ggridges::GeomDensityRidges) geom_density_ridges_pattern <<- ggplot2::make_constructor(GeomDensityRidgesPattern, stat = ggridges::StatDensityRidges, position = ggridges::position_points_sina()) } ``` or write the pattern geom's draw methods yourself (see the next section) as `{ggpattern}` does for its own geoms: a geom made by `ggplot2::ggproto()` looks up the geom it extends each time it is used. If you only need the `geom_*_pattern()` function (and not a `Geom` object) `make_geom_pattern()` given a `geom_*()` function makes the pattern geom each time the function is called (given a geom it stores the pattern geom just like `make_GeomPattern()`). Give it a function that looks the original up when called so that it isn't stored when your package is installed either e.g. `make_geom_pattern(function(...) ggplot2::geom_smooth(...))`. ## Writing a pattern geom's draw methods For full control write the pattern geom's methods yourself: * `default_pattern_aes()` gives the default pattern aesthetics to add to the geom's `default_aes`. Most are `NaN` ("unset") so that each pattern's own defaults apply: copy them with `default_pattern_aes()` rather than writing your own values. * `with_pattern_aes(grob, data)` fills each area of `grob` with the pattern of its row of `data` within a `draw_panel()` or `draw_group()` method. * `with_pattern_key(key, data, size)` fills each area of a key glyph with the key's pattern within a `draw_key()` method (scaling it so the key's pattern looks like the plot's). For example this is essentially how our `GeomHexPattern` is written (the `draw_group()` method of `ggplot2::GeomHex` draws a hexagon per row, in row order): ```{r hex, eval = has_hexbin} GeomHexPattern2 <- ggproto("GeomHexPattern2", GeomHex, default_aes = aes(!!!GeomHex$default_aes, !!!default_pattern_aes()), draw_group = function(self, data, panel_params, coord, ...) { grob <- ggproto_parent(GeomHex, self)$draw_group(data, panel_params, coord, ...) with_pattern_aes(grob, data) # one row per hexagon }, draw_key = function(data, params, size) { with_pattern_key(draw_key_polygon(data, params, size), data, size) } ) ggplot(diamonds, aes(carat, price)) + stat_bin_hex(aes(pattern_fill = after_stat(count) > 1000), geom = GeomHexPattern2, bins = 12, pattern_density = 0.3) + labs(pattern_fill = "count > 1000") ``` Whatever such a geom copies from the geom it extends (here its `default_aes` and in general the arguments of a draw method that names them instead of using `...`) is only as up to date as your package's last build so it is worth testing that they still match. Things to watch out for: * **Row order.** `data` must have a row per area in the order the grob draws them (the order of `gridpattern::area_boundaries(grob)`) or a single row for every area. E.g. `ggplot2::GeomPolygon` draws its groups' polygons sorted by `group` and `ggplot2::GeomPoint` only has areas for its filled shapes (`shape` 21 to 25). Areas that should be filled as one (e.g. the polygons of a `MULTIPOLYGON` geometry) can be given the same value of `pool` (with a row per unique value). * **Areas made when drawn.** If the grob only makes its areas when it is drawn use `with_pattern_aes(grob, data, delay = TRUE)`. * **Other columns.** Besides the pattern aesthetics the other columns of `data` (e.g. `fill`) are passed on to the pattern (for custom patterns that use them) except `x`, `y`, `PANEL`, and the names of `gridpattern::with_pattern()`'s own arguments. * **Key size.** Call `with_pattern_key()` within the `draw_key()` method. `{ggplot2}` may enlarge a key whose glyph has no size attributes after `draw_key()` returns so the `size` it is given can be too small (e.g. `draw_key_point_pattern()` uses the larger of `size` and the point's size). Alternatively subclass one of `{ggpattern}`'s pattern geoms (e.g. `GeomRectPattern` or `GeomPolygonPattern`) to inherit its default aesthetics, draw methods, and legend key.