Cluster data in heat map in R ggplot

后端 未结 3 1041
予麋鹿
予麋鹿 2020-12-29 10:06

Please see my plot below: \"enter

my code:

 > head(data)
                  


        
3条回答
  •  天涯浪人
    2020-12-29 10:34

    You can achieve this by defining the order of Timepoints in a dendrogram after you have applied hclust to your data:

    data <- scale(t(data))
    ord <- hclust( dist(data, method = "euclidean"), method = "ward.D" )$order
    ord
    [1]  2  3  1  4  8  5  6 10  7  9
    

    The only thing you have to do then is transforming your Time-column to a factor where the factor levels are ordered by ord:

    pd <- as.data.frame( data )
    pd$Time <- sub("_.*", "", rownames(pd))
    pd.m <- melt( pd, id.vars = "Time", variable.name = "Gene" )
    
    pd.m$Gene <- factor( pd.m$Gene, levels = colnames(data), labels = seq_along( colnames(data) ) )
    pd.m$Time <- factor( pd.m$Time, levels = rownames(data)[ord],  labels = c("0h", "0.25h", "0.5h","1h","2h","3h","6h","12h","24h","48h") )
    

    The rest is done by ggplot automatically:

    ggplot( pd.m, aes(Time, Gene) ) +
      geom_tile(aes(fill = value)) +
      scale_fill_gradient2(low=muted("blue"), high=muted("red"))
    

    enter image description here

提交回复
热议问题