首页 文章

用R表示含有1和0的矩阵的热图

提问于
浏览
0

下面是我的示例数据,基本上是一个矩阵,其中行名称为人名,每个行都有一些列 . 我在数据中只有零和一个 . 我想用热图来形象化它 . (红色表示0秒,绿色表示1秒或任何其他颜色编码) . 我如何使用R完成此操作?你可以使用任何只有1和0(二进制值)的示例数据集向我展示 .

enter image description here

3 回答

  • 2

    随着 highcharter:

    library(highcharter)
    library(tidyr)
    library(dplyr)
    df<-data.frame(row=c("Dwayne","James"),G=c(1,0),MIN=c(1,0),PTS=c(0,1),FGM=c(0,0),FGA=c(0,0),FGP=c(1,1))
    rownames(df)<-c("Dwayne","James")
    df$row<-rownames(df)
    data<-df%>%
         tidyr::gather(row,value)%>%
         setNames(c("name","variable","value"))
    
    
    hchart(data, "heatmap", hcaes(x = variable, y = name, value = value)) %>% 
      hc_colorAxis(stops = color_stops(2, c("red","green")))
    

    enter image description here
    UPDATE: 你可以为高度= 800添加 hc_size(height = 800) 或者做类似的东西

    x<-50
      hg<-length(unique(data$name))*x+100
    
      hchart(data, "heatmap", hcaes(x = variable, y = name, value = value)) %>% 
        hc_colorAxis(stops = color_stops(2, c("red","green")))%>% 
        hc_size(height = hg)
    

    数据集中的每一行使图表大50点 . 你可以在 x 更改它

  • 0

    只是另一种使用ggplot的方法

    library(ggplot2)
    library(reshape2)
    library(plyr)
    library(scales)
    
    df <- structure(list(people = structure(c(2L, 1L), .Label = c("Dwayne", "LeBron"), class = "factor"),
                     G = c(1L, 0L),
                     MIN = c(1L, 0L),
                     PTS = c(0L, 1L),
                     FGM = c(0L,0L),
                     FGA = c(0L,0L),
                     FGP = c(1L,1L)),
                .Names = c("people", "G", "MIN", "PTS", "FGM", "FGA", "FGP"),
                class = "data.frame",
                row.names = c(NA, -2L))
    
    
    df.m <- melt(df)
    df1.m <- ddply(df.m, .(variable), transform, rescale = value)
    p <- ggplot(df1.m, aes(variable, people)) +
    geom_tile(aes(fill = rescale), colour = "black")
    p + scale_fill_gradient(low = "green", high = "red")
    show(p)
    

    通过tutorial

  • 0

    这个答案使用 plotly ,因此将其添加为另一个答案 . 使用与以下相同的数据 .

    library(plotly)
    df1 <- as.matrix(df)
    p <- plot_ly(x = colnames(df), y = df[,1], z = as.matrix(df[-1]), colors = colorRamp(c("green", "red")), type = "heatmap")
    

    在获取输出方面,这比ggplot2简单得多 .

    希望这可以帮助!

相关问题