Map coloring where some 'grouped' polygons are the same color

EDIT: This has been solved. A solution is to use the dplyr package and use:

mapdata <- mapdata %>% 
  group_by(Group) %>% 
  summarise()

See these:
Merging Geometry of {sf} Objects in R · Jindra Lacko (jla-data.net)
Combine polygons by attribute · Issue #382 · r-spatial/sf · GitHub

Original post:

I have a map of polygons ("Unit") which I want to color. I want adjacent polygons to be different colors, with one exception: if polygons share the same value for the variable "Group", I want them to be the same color.

For some context, I'm working on a project which is merging/grouping together adjacent polygons if they meet certain criteria, and then giving the group a name (this is the "Group" variable, it has no/missing value for polygons that didn't get merged). I want to make this map to help see which polygons have been merged together. Ideally, I'd also like the polygons with a missing "Group" to be coloured a custom colour (maybe grey).

I know that the "MAP_COLORS" option does map colouring the way I want; is there any way to make it give polygons with the same value for the "Group" variable the same color? The other way I've tried to do this is by using the "Group" variable as the coloring col variable, but R tries to give it one colour for every different category and there are way too many categories (there are a lot of "Group" names).

Below is my code.

# Load libraries.
library(leaflet)
library(sp)
library(sf)
library(tmaptools)
library(tmap)
library(leaflet.providers)

#Load Map (change location to where map_reprex is saved)
load("map_reprex.RData")

#Load Color Data (change location to where mapdata_reprex is saved)
load("mapdata_reprex.RData")

#filepath to save maps (change to desired location)
folder<-"C:\\"

# merge the color data onto the map data
merged_data <- merge(mapdata_reprex, map_reprex, all.y=TRUE, by="Unit")

# Make the right type of file
mapdata<-st_as_sf(merged_data)

### mapping Response R
mapRD<- tm_shape(mapdata) +
  tm_fill(col = "MAP_COLORS", title="Test Coloring",colNA="black", textNA="Not grouped")+
  tm_borders(col="black")+
  tm_layout(main.title=paste0("Test Coloring"), main.title.position="center", main.title.size = 1.2)+
  tm_legend(position = c(0.84,0.58), legend.frame=FALSE)

########### save map (.html for interactive, .png for still image)
assign(paste("mapRD_",sep=''), mapRD)
tmap_save(mapRD, paste(folder,"IR",".png",sep=''),units="cm", height=40, width=50)

This topic was automatically closed 42 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.