2
votes

With leaflet() and addPolygons(), it is possible to color polygons (USA states in the example below) according to a specific variable.

Q/ Is there a way to hatch polygons in order to add a second information within the map ?

Color give a first information (cluster belonging), I would like to add a second information (states with 'New' in their name for instance). It could be very useful to visualize the both information at the same time.

library(rgdal)

# From https://www.census.gov/geo/maps-data/data/cbf/cbf_state.html
states <- readOGR(
  dsn   = "2.Data/shp/cb_2013_us_state_20m.shp", 
  layer = "cb_2013_us_state_20m", 
  GDAL1_integer64_policy = T
)

sample <- states %>% 
  subset(STUSPS %in% c("CT","ME","MA","NH","RI","VT","NY","NJ","PA"))

MaPalette1 <- colorFactor(c('red', 'blue', 'green', 'grey', 'black', 'pink', 'orange', 'yellow', 'purple', 'white'), 
                          sample@data$STATEFP)

leaflet(sample) %>%
  addPolygons(
    color       = 'black', 
    weight      = 1,
    fillOpacity = 1,
    fillColor   = ~ MaPalette1(STATEFP)
)

enter image description here

I tried to color the border of the polygons, but as there already are a lot of colors in the map, it is not easy to visualize.

I also tested addLayersControl(), but I really want to visualize information on the same layer, and superposition of two color layers create new colors, the information is not understandable.

Thank in advance for your help. When I said 'hatching', I think something like that:

enter image description here

1

1 Answers

3
votes

Since your question is a few months old, please let me know if you found another solution, and share it. The package HatchedPolygons should do what you're looking for. Below is a working example with the same data that you tried with:

devtools::install_github("statnmap/HatchedPolygons")
library(diplyr)

# From https://www.census.gov/geo/maps-data/data/cbf/cbf_state.html
states <- rgdal::readOGR(
  dsn   = "~/Downloads/cb_2013_us_state_20m/cb_2013_us_state_20m.shp", 
  layer = "cb_2013_us_state_20m", 
  GDAL1_integer64_policy = T
)

sample <- states %>% 
  subset(STUSPS %in% c("CT","ME","MA","NH","RI","VT","NY","NJ","PA"))

MaPalette1 <- colorFactor(c('red', 'blue', 'green', 'grey', 'black', 'pink', 'orange', 'yellow', 'purple', 'white'), sample@data$STATEFP)

# hatching
sample3 <- sample %>% 
  subset(STUSPS %in% c("NH", "NJ")) 
sample3.hatch <- HatchedPolygons::hatched.SpatialPolygons(sample3, density = c(6,4), angle = c(45, 135))

# plot
leaflet(sample) %>%
  addPolygons(
    color       = 'black', 
    weight      = 1,
    fillOpacity = 1,
    fillColor   = ~ MaPalette1(STATEFP)
  ) %>% 
  addPolylines(
    data = sample3.hatch,
    color = c("white", "red"),
    weight = 1.0
  )