Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

visualization - R draw kmeans clustering with heatmap

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...