Search code examples
rleafletr-leaflet

Setting color palettes with different "parent" levels?


I'm trying to color in a map with the leaflet package using data that looks as such:

+--------+---------+-------+
| region | terrain | sales |
+--------+---------+-------+
|      1 | 1A      |   253 |
|      1 | 1B      |   280 |
|      1 | 1C      |   360 |
|      1 | 1D      |   350 |
|      1 | 1E      |   335 |
|      1 | 1F      |   275 |
|      2 | 2A      |   200 |
|      2 | 2B      |   300 |
|      2 | 2C      |   400 |
|      2 | 2D      |   250 |
|      2 | 2E      |   350 |
+--------+---------+-------+

While I know how to create a color palette based off one variable, I would like to create one based on each variables "parent"

So let's say I want 1 = "Reds" and 2 = "Blues" but within those two "parent" colors, I then want all of the terrains within those regions to be shaded in accordance to sales?


Solution

  • You can use library(colourvalues) to generate specific colours for vectors / columns of data

    Setting up data

    ## using a known / reproducible data object
    df <- mapdeck::capitals
    
    ## making a 'region' column to represent your data
    df$region <- ifelse( tolower( substr(df$country,1,1) ) %in% letters[1:13], 1, 2 )
    
    ## a random 'sales' column
    df$sales <- rnorm(n = nrow(df) )
    

    Colouring

    library(colourvalues)
    
    ## order the data first so we can simply `<- c()` the result
    df <- df[with(df, order(region)), ]
    
    
    region1 <- colour_values( x = df[ df$region == 1, "sales"], palette = "reds" )
    region2 <- colour_values( x = df[ df$region == 2, "sales"], palette = "blues")
    
    df$colours <- c(region1, region2)
    

    Plotting

    library(leaflet)
    
    leaflet() %>%
      addTiles() %>%
      addCircles(
        data = df
        , color = df$colours
      )
    

    enter image description here