5

I would like to cluster a matrix with kmeans, and be able to plot it as heatmap. It sounds quite trivial, and I have seen many plots like this. I have tried to google atround, but can't find a way round it.

I'd like to be able to plot something like panel A or B on this figure. Let say I have a matrix with 250 rows and 5 columns. I don't want to cluster the columns, just the rows.

m = matrix(rnorm(25), 250, 5)

km = kmeans(m, 10)

Then how do I plot those 10 clusters as a heatmap ? You comments and helps is more than welcome.

Thanks.

enter image description here

Amro
  • 123,847
  • 25
  • 243
  • 454
Benoit B.
  • 11,854
  • 8
  • 26
  • 29

2 Answers2

6

Something like the following should work:

set.seed(100)
m = matrix(rnorm(10), 100, 5)
km = kmeans(m, 10)
m2 <- cbind(m,km$cluster)
o <- order(m2[, 6])
m2 <- m2[o, ]
library(pheatmap) # I like esoteric packages!
library(RColorBrewer)
pheatmap(m2[,1:5], cluster_rows=F,cluster_cols=F, col=brewer.pal(10,"Set3"),border_color=NA)

heatmap created using the pheatmap pacakge

Paolo
  • 2,795
  • 1
  • 20
  • 23
  • Thanks Paolo for replying. However I am a bit confused, how come we are loosing the 5 columns in the plot ? – Benoit B. Feb 23 '11 at 14:07
  • We are not! Try: pheatmap(m2[,1:5], cluster_rows=F,cluster_cols=F, col=brewer.pal(10,"Set3")) – Paolo Feb 23 '11 at 14:26
0

I think both the two figures should come from two figures combined. the left one is heatmap and the right is colored based on the cluster results. Of course, the data should be reordered by the result of cluster. BTW, the question is not similar with the two questions as commented below the question.

Zhilong Jia
  • 2,329
  • 1
  • 22
  • 34