Carmen Sandoval
Carmen Sandoval

Reputation: 2356

How to make a heatmap of 3 discrete values using ggplot2?

I have a problem with the aes parameters; not sure what it's trying to tell me to fix.

My data frame is like so:

> qualityScores

          Test1  Test2  Test3  Test4 Test5
Sample1      1     2      2      3     1
Sample2      1     2      2      3     2
Sample3      1     2      1      1     3
Sample4      1     1      3      1     1
Sample5      1     3      1      1     2

Where 1 stands for PASS, 2 for WARN, and 3 for FAIL.

Here's the dput of my data:

structure(list(Test1 = c(1L, 1L, 1L, 1L, 1L), Test2 = c(2L, 2L, 
2L, 1L, 3L), Test3 = c(2L, 2L, 1L, 3L, 1L), Test4 = c(3L, 3L, 
1L, 1L, 1L), Test5 = c(1L, 2L, 3L, 1L, 2L)), .Names = c("Test1", 
"Test2", "Test3", "Test4", "Test5"), class = "data.frame", row.names = c("Sample1", 
"Sample2", "Sample3", "Sample4", "Sample5"))

I am trying to make a heatmap where 1 will be represented by gree, 2 by yellow, and 3 by red, using ggplots2.

This is my code:

samples <- rownames(qualityScores)
tests <- colnames(qualityScore)
testScores <- unlist(qualityScores) 

colors <- colorRampPalette(c("red", "yellow", "green"))(n=3)

ggplot(qualityScores, aes(x = tests, y = samples, fill = testScores) ) + geom_tile() + scale_fill_gradient2(low = colors[1], mid = colors[2], high = colors[3])

And I get this error message:

Error: Aesthetics must either be length one, or the same length as the dataProblems:colnames(SeqRunQualitySumNumeric)

Where am I going wrong?

Thank you.

Upvotes: 2

Views: 11513

Answers (1)

MrFlick
MrFlick

Reputation: 206401

This will be much easier if your reshape your data from wide to long format. There are many ways to do that but here I used reshape2

library(reshape2); library(ggplot2)

colors <- c("green", "yellow", "red")

ggplot(melt(cbind(sample=rownames(qualityScores), qualityScores)), 
    aes(x = variable, y = sample, fill = factor(value))) + 
    geom_tile() + 
    scale_fill_manual(values=colors)

enter image description here

Upvotes: 10

Related Questions