Skip to contents

The Layer method of with_pattern() makes a pattern layer from a {ggplot2} layer: the layer's geom is replaced by our pattern geom for it if we have one (e.g. GeomRectPattern for ggplot2::GeomRect) or else by the pattern geom make_GeomPattern() makes from it.

Usage

# S3 method for class 'Layer'
with_pattern(x, ..., mapping = NULL, area_by = NULL)

# S3 method for class 'gg'
with_pattern(x, ...)

# S3 method for class 'Geom'
with_pattern(x, ...)

# S3 method for class 'ggplot'
with_pattern(x, ...)

Arguments

x

A {ggplot2} layer e.g. ggplot2::geom_smooth() (or another {ggplot2} object, which is returned as it is).

...

Pattern aesthetics set to a constant e.g. pattern = "circle" or pattern_fill = "blue".

mapping

Pattern aesthetic mappings (created by ggplot2::aes()) added to those of the layer.

area_by

Passed to make_GeomPattern() (if given the pattern geom is always made by it). It is an error to set it for a layer that already is a pattern layer.

Value

A {ggplot2} layer (or the other {ggplot2} object).

Details

Some {ggplot2} functions return a list instead of a layer e.g. ggplot2::geom_sf() returns a list of a layer and a ggplot2::coord_sf(). The list method of with_pattern() makes a pattern layer from each layer in such a list and the gg method leaves any other {ggplot2} object (which has no areas to fill) as it is (whatever the other arguments) e.g. a coord, scale, facet, theme, ggplot2::labs(), or ggplot2::guides() (a NULL in the list is left as it is too). So e.g. with_pattern(geom_sf(), pattern = "circle") works too. It is an error to give it a plot: give it the plot's layers instead e.g. ggplot(df, aes(x, y)) + with_pattern(geom_col()). It is also an error to give it a geom (e.g. ggplot2::GeomCol): use make_GeomPattern() instead.

To combine it with a {ggfx} filter make the pattern layer first e.g. ggfx::with_blur(with_pattern(geom_col())): the layer of with_pattern(ggfx::with_blur(geom_col())) is drawn without its patterns (since {ggfx} draws the layer with the draw methods of the geom it was given).

See also

make_GeomPattern() to make a pattern geom from a geom.

Examples

library("ggplot2")
if (requireNamespace("magick", quietly = TRUE)) {
  magick::magick_set_seed(42)
  ggplot(mtcars, aes(mpg, wt)) +
      geom_point() +
      with_pattern(geom_smooth(method = "lm", formula = y ~ x),
                   pattern = "plasma", pattern_alpha = 0.7)
}