Search code examples
rggplot2heatmaprgbraster

Creating heatmap from hex code color table in R


I have a hex code color table ("my_table"), as follows:

   V1     V2

1 #010000 #080000

2 #140004 #000000

3 #000000 #080000

4 #040000 #110000

5 #050000 #080004

6 #030000 #030000

7 #090000 #0B0000

8 #3A0010 #2D000D

9 #000000 #000000

I'd like to plot is as a heatmap in R, displaying these colors in my plot. I tried:

grid.raster(my_table, interpolate=FALSE)

and it worked, but I'd also want the heatmap to have labels, a legend, etc. so I thought I'd use a function with more options, like ggplot to plot my heatmaps. I can't find any way to plot this hex code matrix as colors with ggplot, does anyone know a solution?


Solution

  • To get a kind of "literal transcription" of your data frame into a heatmap you can use scale_fill_identity. Your colors are a little dark and difficult to make out, but plotting your data would look something like this:

    library(ggplot2)
    library(dplyr)
    library(tidyr)
    
    my_table %>%
      tibble::rownames_to_column() %>%
      mutate(rowname = as.numeric(rowname)) %>%
      pivot_longer(-1) %>%
      ggplot(aes(x = name, y = rowname, fill = value)) +
      geom_tile(color = "gray50") +
      scale_fill_identity() +
      scale_x_discrete(position = "top") +
      scale_y_reverse(breaks = seq(nrow(my_table))) +
      coord_equal()
    

    You say you want a legend, but it's not clear what the legend would actually show, since the values are actual colors and there seems little point in mapping hex strings to colors in a legend. Unless of course your data structure is actually a bit more complicated than the one in your question.


    Data

    my_table <- structure(list(V1 = c("#010000", "#140004", "#000000", "#040000", 
    "#050000", "#030000", "#090000", "#3A0010", "#000000"), V2 = c("#080000", 
    "#000000", "#080000", "#110000", "#080004", "#030000", "#0B0000", 
    "#2D000D", "#000000")), class = "data.frame", row.names = c("1", 
    "2", "3", "4", "5", "6", "7", "8", "9"))