trevorld / ggpattern

ggplot geoms with pattern fills
https://trevorldavis.com/R/ggpattern/dev/
Other
359 stars 18 forks source link

pattern escaping plot window if R 4.1 clipping enabled #60

Closed trevorld closed 2 years ago

trevorld commented 2 years ago

Bug description

Pattern may escape {ggplot2} plot window if R 4.1 clipping enabled. In particular most likely to affect geoms that have holed polygons such as geom_sf_pattern() and perhaps geom_polygon_pattern().

Minimal, reproducible example

library(ggplot2)
library(sf)
library(rnaturalearth)
library(ggpattern)

shapefile <- ne_countries(continent = 'europe', returnclass = "sf", scale = 110)

options(ggpattern_use_R4.1_clipping = TRUE)
ragg::agg_png("escaping_patterns.png")
ggplot(shapefile) +
  geom_sf_pattern(aes(geometry = geometry, fill = name, pattern_fill = name),
                  pattern = "stripe") +
  xlim(-10, 30) +
  ylim( 37, 60) +
  theme_bw() +
  theme(legend.position = 'none')
dev.off()

escaping_patterns

Workarounds

1) Set options(ggpattern_use_R4.1_clipping = FALSE) to use the raster clipping alternative to the R 4.1 clipping feature

non_escaping_pattern

2) Clip the shapes with {sf} prior to plotting?

Potential future fixes

I guess a grid viewport's clipped setting won't work on clipping paths of interior grobs? Is this a bug in the graphics device that can be fixed? Should we try to manually clip shapes with {sf} in geom_sf_pattern() before plotting?

trevorld commented 2 years ago

9d82d73 should fix this for the geom_sf_pattern() case. If grobs clipped by R 4.1 clipping paths are not clipped by viewports then this could still theoretically happen with geom_polygon_pattern() and perhaps other geoms if you use the "rose", "text", or custom patterns that use the R 4.1 clipping path feature to clip patterns to their polygon boundaries.