我在整个网站和包中搜索了很多关于热图的问题,但我仍然有问题.
我有集群数据(kmeans/EM/DBscan ..),我想通过对同一个集群进行分组来创建热图.我希望将相似的颜色模式分组到热图中,因此通常看起来像块对角线.
我尝试按簇号排序数据并显示它,
k = kmeans(data, 3)
d = data.frame(data)
d = data.frame(d, k$cluster)
d = d[order(d$k.cluster),]
heatmap(as.matrix(d))
Run Code Online (Sandbox Code Playgroud) 但它仍然没有排序,看起来像这个链接:

为此,您可以使用reshape2与ggplot2如下:
library(reshape2)
library(ggplot2)
# Create dummy data
set.seed(123)
df <- data.frame(
a = sample(1:5, 1000, replace=TRUE),
b = sample(1:5, 1000, replace=TRUE),
c = sample(1:5, 1000, replace=TRUE)
)
# Perform clustering
k <- kmeans(df, 3)
# Append id and cluster
dfc <- cbind(df, id=seq(nrow(df)), cluster=k$cluster)
# Add idsort, the id number ordered by cluster
dfc$idsort <- dfc$id[order(dfc$cluster)]
dfc$idsort <- order(dfc$idsort)
# use reshape2::melt to create data.frame in long format
dfm <- melt(dfc, id.vars=c("id", "idsort"))
ggplot(dfm, aes(x=variable, y=idsort)) + geom_tile(aes(fill=value))
Run Code Online (Sandbox Code Playgroud)
