Change Direction of Legend Colorbar in ggplot2

This tutorial explains how to change the direction of legendary color bars of continuous variables. It covers two distinct topics:

If you wish to reorder legend keys of discrete variables, check here instead.

Create a heatmap with continuous colorbar

# packages library(ggplot2)library(dplyr)library(reshape2) # to use the melt function
# set default global themetheme_set(theme_bw() + theme( legend.text = element_text(face = "bold", size = 12)))
# create a demo heatmapp <- volcano %>% melt() %>% ggplot(aes(x = Var1, y = Var2, fill = value)) + geom_raster() + # create heatmap # apply viridis colors palette B scale_fill_viridis_c(option = "B") + # expand heatmap to fill up all plot area coord_cartesian(expand = 0) + # elongate the colorbar theme(legend.key.height = unit(40, "pt")) p

Physically reordient the colorbar (e.g., upside-down)

The code below physically flips the colorbar upside down, while retaining the same color scale; the association between colors and data values remain the same (i.e., large values are depicted in bright yellows, and small values in dark blues, same as the plot above).

p + guides(fill = guide_colorbar(reverse = T))

Invert the color scale

Use the direction argument to invert the color scale, such that large values are mapped in dark blues, and small values in bright yellows. This drastically changes the appearance of the heatmap.

p +   # overwrite the "old" fill scale  # The 'direction' argument takes a binary value of 1 or -1.   scale_fill_viridis_c(option = "B", direction = -1)
Scale for fill is already present.
Adding another scale for fill, which will replace the existing scale.

The direction argument also applies to the color scale using brewer palettes:

p1 <- p + scale_fill_distiller(palette = "Spectral")
p2 <- p + scale_fill_distiller(palette = "Spectral", direction = 1)
library(patchwork)p1 | p2