0

I am working with the R programming language.

I have the following geographical map of North Carolina in R:

library(sf)
library(leaflet)
library(leafgl)
library(colourvalues)
library(leaflet.extras)
library(igraph)

# Load and prepare data
nc <- st_read(system.file("gpkg/nc.gpkg", package = "sf"), quiet = TRUE) %>% 
    st_transform(st_crs(4326)) %>% 
    st_cast("POLYGON")

leaflet(data = nc) %>% addPolygons( stroke = FALSE) %>% addTiles(group = "OSM") %>%  addProviderTiles(provider = providers$OpenStreetMap) %>% addPolygons(data = nc, weight=1, popup = ~NAME,
                label = ~NAME, group = "name", col = 'blue') %>% 
    addSearchFeatures(targetGroups  = 'name', options = searchFeaturesOptions(zoom=10, openPopup=TRUE))

enter image description here

My Question: I would like to color (e.g. 6 random colors - red, blue, green, yellow, purple, orange) each "polygon" on this map such that no two bordering polygons have the same color.

To start this problem, I first converted the geographical map into a network graph:

# Convert to graph
adj <- st_touches(nc, sparse = TRUE)
g <- graph_from_adjacency_matrix(as.matrix(adj))

Then, I took this function that can assign colors to each polygon such that no two bordering polygons have the same color:

# Greedy coloring algorithm (https://igraph.org/r/html/1.3.0/greedy_vertex_coloring.html)
vertex.colors <- c("red", "blue", "green", "yellow", "purple", "orange")

colored.vertices <- greedy_vertex_coloring(g)

Then, I tried to assign these greedy colors to each polygon:

# Assign colors to polygons
poly.colors <- vertex.colors[match(as.character(nc$ID), names(colored.vertices))]
nc$color <- poly.colors

But I get this error:

Error in `[[<-.data.frame`(`*tmp*`, i, value = character(0)) : 
  replacement has 0 rows, data has 108

Had this worked, I would have tried to plot the results:

# Plot map
leaflet(data = nc) %>% 
    addTiles(group = "OSM") %>% 
    addProviderTiles(provider = providers$OpenStreetMap) %>% 
    addPolygons(data = nc, weight = 1, popup = ~NAME,
                label = ~NAME, group = "name",
                fillColor = ~color, fillOpacity = 0.5) %>% 
    addSearchFeatures(targetGroups = "name", options = searchFeaturesOptions(zoom = 10, openPopup = TRUE))

Can someone please show me how to fix this?

Thanks!

stats_noob
  • 5,401
  • 4
  • 27
  • 83

0 Answers0