【发布时间】:2017-08-07 19:35:41
【问题描述】:
我在 ggplot2 上苦苦挣扎,尽管我发现了非常相似的问题,但我没有设法让它工作。我想根据分层聚类按列和行重新排序热图。
这里是我的实际代码:
# import
library("ggplot2")
library("scales")
library("reshape2")
# data loading
data_frame = read.csv(file=input_file, header=TRUE, row.names=1, sep='\t')
# clustering with hclust on row and on column
dd.col <- as.dendrogram(hclust(dist(data_frame)))
dd.row <- as.dendrogram(hclust(dist(t(data_frame))))
# ordering based on clustering
col.ord <- order.dendrogram(dd.col)
row.ord <- order.dendrogram(dd.row)
# making a new data frame reordered
new_df = as.data.frame(data_frame[col.ord, row.ord])
print(new_df) # when mannualy looking new_df it seems working
# get the row name
name = as.factor(row.names(new_df))
# reshape
melte_df = melt(cbind(name, new_df))
# the solution is here to reorder the name column factors levels.
melte_df$name = factor(melte_df$name, levels = row.names(data_frame)[as.vector(row.ord)])
# ggplot2 dark magic
(p <- ggplot(melte_df, aes(variable, name)) + geom_tile(aes(fill = value),
colour = "white") + scale_fill_gradient(low = "white",
high = "steelblue") + theme(text=element_text(size=12),
axis.text.y=element_text(size=3)))
# save fig
ggsave(file = "test.pdf")
# result is ordered as only by column what I have missed?
如果你能提出你的答案,我是 R 的新手。
【问题讨论】:
标签: r ggplot2 heatmap hierarchical-clustering