Search code examples
rcolorspalette

How to display multiple custom colour palettes in a single figure with R


To expand upon visualize a list of colors/palette in R I am trying to display a series of custom colour palettes in R in a single figure. Is there a way that I can expand on one of the methods listed in the link to display the list of palettes below:

convert_coolers <- function(coolers_string){
  strsplit(coolers_string, split = ", ")[[1]]
}

# diverging
storm_panels <- convert_coolers("#001219, #005f73, #0a9396, #94d2bd, #e9d8a6, #ee9b00, #ca6702, #bb3e03, #ae2012, #9b2226")
harry_tipper <- convert_coolers("#f72585, #b5179e, #7209b7, #560bad, #480ca8, #3a0ca3, #3f37c9, #4361ee, #4895ef, #4cc9f0")
firepit <- convert_coolers("#03071e, #370617, #6a040f, #9d0208, #d00000, #dc2f02, #e85d04, #f48c06, #faa307, #ffba08")

# sequences
the_deep <- convert_coolers("#03045e, #023e8a, #0077b6, #0096c7, #00b4d8, #48cae4, #90e0ef, #ade8f4, #caf0f8")
earth <- convert_coolers("#ede0d4, #e6ccb2, #ddb892, #b08968, #7f5539, #9c6644")

# categorical
pastal_rainbow <- convert_coolers("#ff595e, #ffca3a, #8ac926, #1982c4, #6a4c93")
fisherman <- convert_coolers("#353535, #3c6e71, #ffffff, #d9d9d9, #284b63")

in a figure resembling that displayed by RColorBrewer::display.brewer.all()? i.e. with palettes stacked as horizontal bars labelled to the left with the palette title. I have been trying to dissect the method out from the RColorBrewer function but am finding that it depends too much on internal variables for me to understand what is going on.


Solution

  • I achieved what I set out to do by modifying RColorBrewer::display.brewer.all

    Following directly on from the code in the question:

    display_custom_palettes <- function(palette_list, palette_names){
      nr <- length(palette_list)
      nc <- max(lengths(palette_list))
      ylim <- c(0, nr)
      oldpar <- par(mgp = c(2, 0.25, 0))
      on.exit(par(oldpar))
      plot(1, 1, xlim = c(0, nc), ylim = ylim, type = "n", axes = FALSE, 
           bty = "n", xlab = "", ylab = "")
      for (i in 1:nr) {
        nj <- length(palette_list[[i]])
        shadi <- palette_list[[i]]
        rect(xleft = 0:(nj - 1), ybottom = i - 1, xright = 1:nj, 
             ytop = i - 0.2, col = shadi, border = "light grey")
      }
      text(rep(-0.1, nr), (1:nr) - 0.6, labels = palette_names, xpd = TRUE, 
           adj = 1)
    }
    
    plot.new()
    
    palette_list <- list(storm_panels, harry_tipper, firepit, the_deep, earth, pastal_rainbow, fisherman)
    palette_names <- c("storm panels", "harry tipper", "firepit", "the deep", "earth", "rainbow", "fisherman")
    
    display_custom_palettes(palette_list, palette_names)