R:: fill based on symbols like strokes, lines and dots instead of colours in ggplot

Viewed 390

Im interested to know if one can plot a map or any graph by using lines, strokes, points and other symbols instead of colors in ggplot ?

For example instead of such a map :

 if (requireNamespace("sf", quietly = TRUE)) {
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
ggplot(nc) +
  geom_sf(aes(fill = AREA))

which would result in a plot like this: Result of a map (which i dont want like)

Instead of such a map, is it possible to fill with symbols like

Fill based on this

2 Answers

You may want to check out ggpattern.

Specifically the code in this example:

library(maps)

crimes <- data.frame(state = tolower(rownames(USArrests)), USArrests)
crimesm <- reshape2::melt(crimes, id = 1)

states_map <- map_data("state")

p <- ggplot(crimes, aes(map_id = state)) +
    geom_map_pattern(
      map = states_map,
      aes(
        pattern_type = state
      ),
      pattern              = 'magick',
      pattern_fill         = 'black',
      pattern_aspect_ratio = 1.75,
      fill                 = 'white',
      colour               = 'black',
    ) +
    expand_limits(x = states_map$long, y = states_map$lat) +
    coord_map() +
    theme_bw(18) +
    labs(title = "ggpattern::geom_map_pattern()") +
  labs(
    title = "ggpattern::geom_map_pattern()",
    subtitle = "pattern = 'magick'"
  ) +
    scale_pattern_type_discrete(choices = ggpattern::magick_pattern_names) +
    theme(legend.position = 'none')

p



You can even use ggpattern directly with sf objects through geom_sf_pattern like this:

devtools::install_github("coolbutuseless/ggpattern")
library(sf)
library(ggplot2)
library(ggpattern)

nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)

# here is where the magic happens
ggplot(nc) +
  geom_sf_pattern(aes(pattern=substr(NAME, 1,1)))

enter image description here

Find a detailed description of the ggpattern package here

Related