Invert continuous color scale legend in ggplot geom_tile heatmap

2.3k Views Asked by At

Minimal example:

library(ggplot2)
x <- c(1:3)
y <- c(1:3)
data <- expand.grid(X=x, Y=y)
data$Z <- runif(9)
ggplot(data, aes(X, Y, fill=Z)) +
  geom_tile()

Produces this:

plot

How do you get the Z scale bar on the right to run from 0 on top to 1 on the bottom? instead of from bottom to top?

I'm trying to emphasize smaller values, and actually would like for this to work with viridis or magma color scheme if possible. But direction=-1 on scale_fill_viridis only flips the color scale. Would like yellow = 0, blue/black = 1. Then Z scale to go from blue to yellow from bottom to top.

ggplot(data, aes(X, Y, fill=Z)) +
  geom_tile() +
  scale_fill_viridis(discrete=FALSE, direction=-1)

viridis

2

There are 2 best solutions below

0
On

In the scale_fill_distiller you can select the palette and the direction of the palette.

library(ggplot2)
x <- c(1:3)
y <- c(1:3)
data <- expand.grid(X=x, Y=y)
data$Z <- runif(9)


ggplot(data) +
  aes(x = X, y = Y, fill = Z) +
  geom_tile(size = 1L) +
  scale_fill_distiller(palette = "Blues", direction = 1) +
  theme_minimal()

0
On

I got it to work with trans = 'reverse'

ggplot(data, aes(X, Y, fill=Z)) +
  geom_tile() + 
  scale_fill_viridis(trans = 'reverse', option="plasma")

enter image description here