ggpattern

repository·master·Indexed 19 days ago

https://github.com/trevorld/ggpattern

An R package that extends ggplot2 by providing custom geoms capable of filling areas with geometric or image-based patterns. It provides pattern-equivalent versions of nearly all fillable ggplot2 geoms (e.g., geom_col_pattern, geom_boxplot_pattern) and introduces pattern-specific aesthetics such as pattern_fill, pattern_density, and pattern_angle to control appearance.

Tokens
5.7K
Snippets
5
Records
12
Agent score
14%

What's inside ggpattern

  1. Control pattern appearance with new aesthetics

    master

    To customize how patterns look in your plots, ggpattern provides a set of pattern-specific aesthetics. These can be mapped to variables in aes() or set directly. Note that not all aesthetics apply to every pattern; you should check the specific pattern's vignette or the aesthetic use by pattern table for compatibility.

    Commonly used aesthetics include:

    • pattern: The name of the pattern (e.g., 'stripe', 'crosshatch', 'circle', 'image', 'magick', 'gradient').
    • pattern_alpha: Transparency of the pattern (range [0, 1]).
    • pattern_density: Fraction of area the pattern fills (range [0, 1]).
    • pattern_colour: Stroke colour.
    • pattern_fill: Fill colour.
    • pattern_angle: Rotation angle in degrees.
    • pattern_spacing: Spacing between repetitions (range [0, 1] in npc units).
    • pattern_filename: Filename or URL for image-based patterns.
  2. Use scale functions for pattern aesthetics

    master
    Just like standard ggplot2 scales, ggpattern provides scale functions to control pattern aesthetics. For example, you can use scale_pattern_alpha_discrete() to control how pattern alpha is mapped to data.
  3. Quickstart with ggpattern geoms

    master

    To use patterns in your ggplot2 plots, follow these three steps:

    1. Identify an existing plot using a ggplot2 geom with a fillable area (e.g., geom_col()).
    2. Replace that geom with its {ggpattern} equivalent (e.g., ggpattern::geom_col_pattern()).
    3. Set the pattern aesthetic to your desired pattern (e.g., pattern = 'stripe') and use pattern_* aesthetics to control appearance.

    Example of a striped bar chart:

    df <- data.frame(level = c("a", "b", "c", 'd'), outcome = c(2.3, 1.9, 3.2, 1))
    
    ggplot(df) +
      geom_col_pattern(
        aes(level, outcome, pattern_fill = level), 
        pattern = 'stripe',
        fill    = 'white',
        colour  = 'black'
      ) +
      theme_bw(18) +
      theme(legend.position = 'none') +
      labs(
        title    = "ggpattern::geom_col_pattern()",
        subtitle = "pattern = 'stripe'"
      ) +
      coord_fixed(ratio = 1/2)
  4. Install ggpattern

    master

    You can install ggpattern using several methods depending on whether you want the CRAN release or the development version.

    CRAN Release

    Install the stable version from CRAN:

    install.packages("ggpattern")

    Note: The CRAN version omits several vignettes included in the development version.

    Development Version (R-universe)

    To get the latest features and full documentation, install from R-universe:

    install.packages('ggpattern', repos = c('https://trevorld.r-universe.dev', 'https://cloud.r-project.org'))

    Development Version (GitHub)

    Install directly from the GitHub source using the {remotes} package:

    # install.packages("remotes")
    remotes::install_github("trevorld/ggpattern")

    System Dependencies

    Depending on your OS, you may need to install system libraries manually (using apt, brew, dnf, etc.). As of June 2025, ggpattern depends on {gridpattern}, which relies on {sf}, {s2}, and {units}. This may require system development libraries for:

    • Abseil
    • OpenSSL
    • udunits2

    If installation fails, check your error messages for the specific missing system library.

    install.packages("ggpattern")
  5. Create user-defined patterns

    master
    Users can write their own pattern functions and use them with ggpattern without needing to include the pattern in the package itself. For detailed instructions on how to implement these, see the developing-patterns vignette: vignette("developing-patterns", package = "ggpattern").
  6. Quickstart: Use pattern geoms in ggplot2

    master

    To use patterns, replace a standard ggplot2 geom with its ggpattern equivalent (e.g., use geom_col_pattern() instead of geom_col()). You can then control the pattern appearance using the pattern aesthetic and various pattern_* aesthetics.

    1. Identify a ggplot2 geom with a fillable area.
    2. Use the corresponding ggpattern version.
    3. Set pattern to a value like 'stripe'.
    4. Use pattern_* aesthetics to customize (e.g., pattern_fill).
    library(ggplot2)
    library(ggpattern)
    
    df <- data.frame(level = c("a", "b", "c", 'd'), outcome = c(2.3, 1.9, 3.2, 1))
    
    ggplot(df) +
      geom_col_pattern(
        aes(level, outcome, pattern_fill = level), 
        pattern = 'stripe',
        fill    = 'white',
        colour  = 'black'
      ) +
      theme_bw(18) +
      theme(legend.position = 'none') +
      labs(
        title    = "ggpattern::geom_col_pattern()",
        subtitle = "pattern = 'stripe'"
      ) +
      coord_fixed(ratio = 1/2)
  7. Troubleshoot common ggpattern limitations

    master

    When working with ggpattern, be aware of the following known limitations and workarounds:

    • Aspect Ratio: If the internal aspect ratio calculation is incorrect, use pattern_aspect_ratio to override it.
    • Legend Rendering: Legend rendering for patterns is currently limited. Use pattern_key_scale_factor to adjust the appearance of patterns in the legend.
    • Performance: The RStudio output device can be slow when rendering plots with many patterns. For better performance, save your plots directly to PNG or PDF.
    • Geometry Issues: Self-intersecting geometry can cause issues.
    • Coordinate Systems: Non-linear coordinate systems have not been tested.
  8. Available ggpattern geoms

    master

    The {ggpattern} package provides custom versions of nearly all ggplot2 geoms that support fillable areas. These are named by appending _pattern to the original ggplot2 geom name.

    ggplot2ggpattern
    geom_areageom_area_pattern
    geom_bargeom_bar_pattern
    geom_bin2dgeom_bin2d_pattern
    geom_boxplotgeom_boxplot_pattern
    geom_colgeom_col_pattern
    geom_crossbargeom_crossbar_pattern
    geom_densitygeom_density_pattern
    geom_histogramgeom_histogram_pattern
    geom_mapgeom_map_pattern
    geom_polygongeom_polygon_pattern
    geom_rectgeom_rect_pattern
    geom_ribbongeom_ribbon_pattern
    geom_sfgeom_sf_pattern
    geom_tilegeom_tile_pattern
    geom_violingeom_violin_pattern
  9. Reference: ggpattern pattern aesthetics

    master

    The following table lists the available pattern aesthetics and their properties. Use these within aes() to map pattern properties to data or set them globally to control pattern appearance.

    | aesthetic                | description                                   | default    | possible values                                                              |
    |--------------------------|-----------------------------------------------|------------|------------------------------------------------------------------------------|
    | `pattern`                  | Name of the pattern to draw                   | 'stripe'   | stripe, crosshatch, circle, image, placeholder, magick, gradient, plasma     |
    | `pattern_type`             | Generic control option                        | NA         | pattern-dependent                                                           |
    | `pattern_subtype`          | Generic control option                        | NA         | pattern-dependent                                                           |
    | `pattern_alpha`            | Alpha                                         | 1          | value in range [0, 1] (npc units)                                           |
    | `pattern_linetype`         | Stroke linetype                               | 1          | linetype                                                                    |
    | `pattern_size`             | Stroke linewidth                              | 1          | linewidth                                                                   |
    | `pattern_shape`            | Plotting shape                                | 1          | shapes                                                                       |
    | `pattern_colour`           | Stroke colour                                 | 'grey20'   | colour                                                                       |
    | `pattern_fill`             | Fill colour                                   | 'grey80'   | colour                                                                       |
    | `pattern_fill2`            | Second fill colour                            | '#4169E1'  | colour                                                                       |
    | `pattern_angle`            | Rotation angle                                | 30         | angle in degrees                                                            |
    | `pattern_density`          | Approx. fraction of area the pattern fills    | 0.2        | value in range [0, 1] (fraction)                                            |
    | `pattern_spacing`         | Spacing between repetitions of pattern        | 0.05       | value in range [0, 1] (npc units)                                           |
    | `pattern_xoffset`          | Shift pattern along x axis                    | 0          | value in range [0, 1] (npc units)                                           |
    | `pattern_yoffset`          | Shift pattern along y axis                    | 0          | value in range [0, 1] (npc units)                                           |
    | `pattern_aspect_ratio`     | Aspect ratio adjustment                       | NA         | usual range [0.01, 10]                                                      |
    | `pattern_key_scale_factor` | Scale factor for pattern in legend            | 1          |                                                                              |
    | `pattern_filename`         | Image filename/URL                            | ''         | Filename/URL                                                                 |
    | `pattern_gravity`          | Image placement                               | 'center'   | `ggpattern::magick_gravity_names`                                           |
    | `pattern_filter`           | Image scaling filter                          | 'lanczos'  | `ggpattern::magick_filter_names`                                             |
    | `pattern_scale`            | Scale                                         | 1          | Multiplier                                                                   |
    | `pattern_orientation`      | Orientation                                   | 'vertical' | 'vertical', 'horizontal', 'radial'                                          |
    | `pattern_phase`            | Phase                                         | 0          |                                                                              |
    | `pattern_frequency`        | Frequency                                     | 0.1        |                                                                              |
    | `pattern_option_1 - 5`     | Generic options for expansion                | 0          |                                                                              |
    | `pattern_grid`             | Grid type                                     | 'square'   | 'square', 'hex', 'hex_circle'                                               |
    | `pattern_res`              | Pattern resolution (pixels per inch)          | NA         | Resolution                                                                   |
    | `pattern_rot`              | Shape rotation angle (within pattern)         | 0          | angle in degrees                                                            |
  10. Troubleshooting and Limitations

    master

    When using ggpattern, be aware of the following:

    • Aspect Ratio: Use pattern_aspect_ratio to override internal aspect ratio calculations.
    • Legend Rendering: Legend rendering for patterns is currently limited. Use pattern_key_scale_factor to adjust the appearance of patterns in the legend.
    • Performance: The RStudio output device can be slow for plots with many patterns. For better performance, save plots directly to PNG or PDF.
    • Geometry Issues: Self-intersecting geometry can cause issues.
    • Coordinates: Non-linear coordinate systems have not been tested.
  11. Pattern aesthetics and scale functions

    master

    To control pattern appearance, use the following aesthetics. Note that not all aesthetics apply to all patterns; refer to specific pattern vignettes for compatibility. You can also use scale functions like scale_pattern_alpha_discrete to control these values.

    | aesthetic | description | default | possible values |
    |---|---|---|---|
    | `pattern` | Name of the pattern to draw | 'stripe' | stripe, crosshatch, circle, image, placeholder, magick, gradient, plasma |
    | `pattern_type` | Generic control option | NA | pattern-dependent |
    | `pattern_subtype` | Generic control option | NA | pattern-dependent |
    | `pattern_alpha` | Alpha | 1 | value in range [0, 1] (npc units) |
    | `pattern_linetype` | Stroke linetype | 1 | linetype |
    | `pattern_size` | Stroke linewidth | 1 | linewidth |
    | `pattern_shape` | Plotting shape | 1 | shapes |
    | `pattern_colour` | Stroke colour | 'grey20' | colour |
    | `pattern_fill` | Fill colour | 'grey80' | colour |
    | `pattern_fill2` | Second fill colour | '#4169E1' | colour |
    | `pattern_angle` | Rotation angle | 30 | angle in degrees |
    | `pattern_density` | Approx. fraction of area the pattern fills | 0.2 | value in range [0, 1] (fraction) |
    | `pattern_spacing` | Spacing between repetitions of pattern | 0.05 | value in range [0, 1] (npc units) |
    | `pattern_xoffset` | Shift pattern along x axis | 0 | value in range [0, 1] (npc units) |
    | `pattern_yoffset` | Shift pattern along y axis | 0 | value in range [0, 1] (npc units) |
    | `pattern_aspect_ratio` | Aspect ratio adjustment | NA | usual range [0.01, 10] |
    | `pattern_key_scale_factor` | Scale factor for pattern in legend | 1 | |
    | `pattern_filename` | Image filename/URL | '' | Filename/URL |
    | `pattern_gravity` | Image placement | 'center' | `ggpattern::magick_gravity_names` |
    | `pattern_filter` | Image scaling filter | 'lanczos' | `ggpattern::magick_filter_names` |
    | `pattern_scale` | Scale | 1 | Multiplier |
    | `pattern_orientation` | Orientation | 'vertical' | 'vertical', 'horizontal', 'radial' |
    | `pattern_phase` | Phase | 0 | |
    | `pattern_frequency` | Frequency | 0.1 | |
    | `pattern_option_1 - 5` | Generic options for expansion | 0 | |
    | `pattern_grid` | Grid type | 'square' | 'square', 'hex', 'hex_circle' |
    | `pattern_res` | Pattern resolution (pixels per inch) | NA | Resolution |
    | `pattern_rot` | Shape rotation angle (within pattern) | 0 | angle in degrees |