R Draw Kmeans Clustering with Heatmap

R draw kmeans clustering with heatmap

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

Group variables by clusters on heatmap in R

Turned out this was extremely easy. I am still posting the solution so others in my case don't waste time on that like I did.

The first part is exactly the same as before:

data.m=melt(data)
data.m[,"rescale"]=round(rescale(data.m[,"value"]),3)

Now, the trick is that the levels of the factors of the melted data.frame have to be ordered by membership:

data.m[,"X1"]=factor(data.m[,"X1"],levels=levels(data.m[,"X1"])[order(membership)])
data.m[,"X2"]=factor(data.m[,"X2"],levels=levels(data.m[,"X2"])[order(membership)])

Then, plot the heat map (same as before):

p=ggplot(data.m,aes(X1, X2))+geom_tile(aes(fill=rescale),colour="white") 
p=p+scale_fill_gradient(low="white",high="black")
p+theme(text=element_text(size=10),axis.text.x=element_text(angle=90,vjust=0))

Sample Image

This time, the cluster is clearly visible.



Related Topics



Leave a reply



Submit