Skip to contents

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 three 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_GeomPattern() makes a pattern geom from a geom, for a reusable geom_*_pattern() function.
  3. Writing the pattern geom’s draw methods yourself with with_pattern_aes() and with_pattern_key(), for full control.

All three 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):

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_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:

GeomSmoothPattern <- make_GeomPattern(GeomSmooth)
geom_smooth_pattern <- make_constructor(GeomSmoothPattern, stat = "smooth", se = TRUE)

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)

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 stat = "smooth" above. Likewise a constructor argument’s default is taken from the geom’s draw method which may differ from that of its geom_*() function: 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(), hence se = TRUE above. Without the stat the layer may fail with an error about missing aesthetics the stat would have computed e.g. ggridges::geom_density_ridges() needs stat = "density_ridges" (which computes height) and position = "points_sina":

library("ggridges")
GeomDensityRidgesPattern <- make_GeomPattern(GeomDensityRidges)
geom_density_ridges_pattern <- make_constructor(GeomDensityRidgesPattern,
                                                stat = "density_ridges", position = "points_sina")

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 built, 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 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:

GeomSmoothPattern <- NULL
geom_smooth_pattern <- NULL

.onLoad <- function(libname, pkgname) {
  GeomSmoothPattern <<- ggpattern::make_GeomPattern(ggplot2::GeomSmooth)
  geom_smooth_pattern <<- ggplot2::make_constructor(GeomSmoothPattern, stat = "smooth", se = TRUE)
}

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.

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):

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.