MDStat
MDStat

Reputation: 435

R heatmap: assign colors to values

I've found the following R code in the R graph gallery (https://www.r-graph-gallery.com/79-levelplot-with-ggplot2.html) for a heatmap and modified it a little bit:

# Library
library(ggplot2)

set.seed(10)

# Dummy data
x <- LETTERS[1:20]
y <- paste0("var", seq(1,20))
data <- expand.grid(X=x, Y=y)
data$Z <- runif(400, -1, 2)

print (data)

# Heatmap 
ggplot(data, aes(X, Y, fill= Z)) + 
  geom_tile(color = "white",
            lwd = 0.5,
            linetype = 1)

My issue: I have three columns with values ranging from -1 to 2. Now I would like to assign defined colors to the values, f.e. as follows: -1: color red, 0: color green, 1: color yellow, 2: color blue.

Is there a way to use the geom_tile function for my issue?

Thank you!

Upvotes: 2

Views: 3150

Answers (2)

Pedro Alencar
Pedro Alencar

Reputation: 1089

If you want to have discrete intervals and scale, you should get the values of df$Z into integer factors and then use scale_fill_manual to get the desired colour scheme.

data$Z <- factor(round(data$Z))

# Heatmap 
ggplot(data, aes(X, Y, fill= Z)) + 
    geom_tile(color = "white",
              lwd = 0.5,
              linetype = 1)+
    scale_fill_manual(values = c('red', 'green', 'yellow', 'blue'))

#or simply

ggplot(data, aes(X, Y, fill= factor(round(data$Z)))) + 
    geom_tile(color = "white",
              lwd = 0.5,
              linetype = 1)+
    scale_fill_manual(values = c('red', 'green', 'yellow', 'blue'), name = 'Z')

enter image description here

To transform the Z values into strings you can use:

library(plyr)

data$Z <- factor(round(data$Z))

ata$Z <- revalue(data$Z, c('-1'='negative'))
data$Z <- revalue(data$Z, c('0' = 'no'))
data$Z <- revalue(data$Z, c('1' = 'yes'))
data$Z <- revalue(data$Z, c('2' = 'other'))

# Heatmap 
ggplot(data, aes(X, Y, fill= Z)) + 
    geom_tile(color = "white",
              lwd = 0.5,
              linetype = 1)+
    scale_fill_manual(values = c('red', 'green', 'yellow', 'blue'), name = 'Z')

enter image description here

Upvotes: 2

MrFlick
MrFlick

Reputation: 206546

you can use scale_gradient_n for that

ggplot(data, aes(X, Y, fill= Z)) + 
  geom_tile(color = "white",
            lwd = 0.5,
            linetype = 1) + 
  scale_fill_gradientn(breaks=c(-1, 0, 1, 2), colors=c("red","green","yellow","blue"))

Those colors seem to produce quite the sight enter image description here

Upvotes: 1

Related Questions