Search code examples
rggplot2heatmapcolorbrewer

Reverse color brewer colors of a ggplot heatmap


library(tidyverse)
library(RColorBrewer)
x <- LETTERS[1:20]
y <- paste0("var", seq(1, 20))
data <- expand.grid(X = x, Y = y)
data$Z <- runif(400, 0, 5)

If I construct the data frame above, and then plot a heat map with the code below I get this and that:

ggplot(data, aes(X, Y, fill = Z)) + 
  geom_tile() +
  scale_fill_distiller(palette = "Reds") +                    # line 3
  # scale_fill_distiller(palette = "Reds", direction = -1) +  # line 4
  labs(x = NULL, y = NULL) +
  theme_minimal()

I thought running line #4 in place of line #3 (above) was supposed to reverse the colors of my legend, according to ?scale_fill_distiller():

direction argument: Sets the order of colours in the scale. If 1, the default, colours are as output by RColorBrewer::brewer.pal(). If -1, the order of colours is reversed.

In essence the white areas of the heat map would turn dark red, and the dark red areas of the heat map would turn white. Why isn't this happening? Run line #3 above, or line #4 and the output is the same.

heatmap


Solution

  • Further to my comment above, let's put both plots side-by-side

    gg1 <- ggplot(data, aes(X, Y, fill = Z)) +
        geom_tile() +
        scale_fill_distiller(palette = "Reds", direction = +1) +
        labs(x = NULL, y = NULL) +
        theme_minimal()
    
    gg2 <- ggplot(data, aes(X, Y, fill = Z)) +
        geom_tile() +
        scale_fill_distiller(palette = "Reds", direction = -1) +
        labs(x = NULL, y = NULL) +
        theme_minimal()
    
    library(gridExtra)
    g <- grid.arrange(gg1, gg2)
    

    enter image description here

    The reason for the behaviour you see above is due to scale_fill_distiller assuming direction = -1 by default:

    scale_fill_distiller
    #function (..., type = "seq", palette = 1, direction = -1, values = NULL,
    #    space = "Lab", na.value = "grey50", guide = "colourbar",
    #    aesthetics = "fill")
    #{
    #    type <- match.arg(type, c("seq", "div", "qual"))
    #    if (type == "qual") {
    #        warning("Using a discrete colour palette in a continuous scale.\n  Consider using type = \"seq\" or type = \"div\" instead",
    #            call. = FALSE)
    #    }
    #    continuous_scale(aesthetics, "distiller", gradient_n_pal(brewer_pal(type,
    #        palette, direction)(7), values, space), na.value = na.value,
    #        guide = guide, ...)
    #}
    #<bytecode: 0x7fed742ed1d8>
    #<environment: namespace:ggplot2>