Pattern in ggpattern doesn't follow polygon borders after update

Viewed 347

I made some maps with spatial features from the sf package and used ggpattern to create a striped fill. This worked well for certain polygons, but not for those with holes in it (islands in a lake feature class).

Recently the ggpattern package has been updated to work with polygons with holes (for which I am grateful!), and it no longer gives errors for these features but now the pattern fill is wrong for all features (with and without holes), since it no longer follows the polygon borders but instead fills a rectangle around the polygons.

Here's an example using the rnaturalearth package to show what I mean.

#devtools::install_github("coolbutuseless/ggpattern")
library(ggpattern)
library(rnaturalearth)

germany <- ne_countries(country='germany', returnclass='sf')
ggplot() + geom_sf_pattern(data = germany)

This gives me this as a result.

this

And here are pictures of my actual map before and after the ggpattern update for polygons without holes, using unchanged code and data.

I've looked through the ggpattern page to see if I am missing certain parameters that I need to change, but can't seem to find the issue. I am relatively new to R so maybe I overlooked something. Would appreciate any help to point me in the right direction!

2 Answers

I got the same issue. If you go on Github it's bug already reported. However, the solution proposed doesn't work for me. So I propose you an alternative solution.

devtools::install_github("statnmap/HatchedPolygons")
require(HatchedPolygons)
require(rnaturalearth)
    
ger <- st_as_sf(germany)

hatch <- hatched.SpatialPolygons(ger, density = 4, angle = 45)
hatch <- hatch %>% sf::st_set_crs(st_crs(germany))

ggplot(germany) + 
  geom_sf() +
  geom_sf(data = hatch)

enter image description here

If you want specific hatched regions, you should first create the hatched polygon desired and then clip it to your data and finally you plot it as sf object.

Please update your {ggpattern} and {gridpattern} packages to the latest (development) versions using remotes::install_github(coolbutuseless/ggpattern). There were some issues with geom_sf_pattern() pattern clipping/masking which were fixed last week (Jan. 16th-20th, 2022). Theoretically it should work now. You shouldn't need to use a different OS.

If it still doesn't work some workarounds to try:

  1. Explicitly turn off (or on) R 4.1 features with options(ggpattern_use_R4.1_features = FALSE). Normally this shouldn't explicitly be needed since {gridpattern} can guess R 4.1 support in the active graphics device...

  2. Save images using a different graphics device such as pdf() or ragg::agg_png() instead of the default interactive windows device. Use a pdf/png viewer that automatically refreshes when image file is over-written.

Related