Search code examples
rcolorspolygon

How to assign pre-determined RGB values to polygons


I have a map defined by polygons in a shape file that I have read into R. Each polygon has a character value assigned to it in a column called "UNIT_250K", and each of those character values has it's own RGB values provided in 3 columns called "RED", "GREEN", and "BLUE". I need to color the polygons using the RGB values but my attempts to do so aren't working.

This is what I tried:

tm_shape(YGS_GLGY) +
  tm_polygons(fill = rgb(red = "RED", green = "GREEN", blue = "BLUE")) +
  tm_borders()

Solution

  • You can create a new column with your RGB values converted to their corresponding hex values and use that column to fill your polygons. As you did not provide sample data, this reprex uses the built-in nc dataset from the sf package, and assumes your RGB values are scaled from 0-1. If not, you need to scale them first by dividing by 255.

    library(tmap)
    library(sf)
    library(dplyr)
    
    # Sample data with scaled (0 - 1) RGB values
    set.seed(42)
    YGS_GLGY <- st_read(system.file("shape/nc.shp", package = "sf")) |>
      mutate(RED = sample(0:255, n()) / 255,
             GREEN = sample(0:255, n()) / 255,
             BLUE = sample(0:255, n()) / 255)
    
    # Generate hex values in a new column
    YGS_GLGY <- YGS_GLGY |>
      mutate(fill = rgb(RED, GREEN, BLUE))
    
    # Plot
    tm_shape(YGS_GLGY) +
      tm_polygons(fill = "fill") +
      tm_borders()
    

    1