ggplot2 pattern fill polygons by variable

I want this (left image), but instead of purple for the third fill option, I want it striped red & blue (right image).

Essentially, I want to merge these two codes:

State Code:

party_color <- c('red', 'blue', 'purple')

ggplot(data = id, mapping = aes(x = long, y = lat, group = group)) +
  geom_polygon(data = id, aes(fill = party), color = "black") +
  scale_fill_gradientn(colours = party_color) +
  coord_map() +
  theme_bw() +
  theme(legend.position="none") +

Stripe Code:

polygon_df <- dplyr::tibble(
  angle = seq(0, 2*pi, length.out = 7) + pi/6,
  x     = cos(angle),
  y     = sin(angle)

ggplot(polygon_df) +
    aes(x = x, y = y),
    pattern = 'stripe',
    fill = 'red',
    pattern_fill = 'blue',
    color = 'black'
    ) +
  coord_equal() +
  coord_map() +
  theme_bw() +

How do I get the purple counties to be filled like the hexagon above? I need it to be a ggplot2 solution using geom_polygon. It doesn't necessarily have to be a ggpattern solution, but I like the look of the ggpattern, so that's why I am trying to use that, but all the examples I can find are for a single polygon, or using geom_map---not what I want to use.

Any state or country polygon example will work. I didn't include the "id" dataset because it is very large.

Thank you so much in advance!

library(ggpattern) #renv::install("coolbutuseless/ggpattern")

nz <- map_data("nz")
# Prepare a map of NZ
nzmap <- ggplot(nz, aes(x = long,
                        y = lat, 
                        group = group)) +
    pattern = 'stripe',
    fill = 'red',
    pattern_fill = 'blue',
    color = 'black'


Thank you for your response. Unfortunately, that is how I created my hex above. I can easily reproduce this for any single polygon, but I can't figure out how to apply it across multiple polygons. When I try to apply it to my map as you posted, it fills the entire state with that, not individual counties.


states_map <- map_data("state") %>%
  filter(long < -100)

p <- ggplot(states_map %>% distinct(region), aes(map_id = region)) +
    map = states_map,
      pattern_angle = region
    pattern = "stripe",
    pattern_fill = "purple",
    pattern_aspect_ratio = 1.75,
    fill = "red",
    colour = "black",
  ) +
  scale_pattern_type_discrete(choices = ggpattern::magick_pattern_names) +
  expand_limits(x = states_map$long, y = states_map$lat) +

Thanks again. Two questions.

  1. is there a way to do that, but with the pattern only on selected polygons, and not all of them? So some are all red, some are all blue, and others are the pattern?

  2. This is not as important, but is there no way to do it using geom_polygon_pattern? I noticed you used geom_map_pattern.

Thanks again for all your hard work!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.