代码之家  ›  专栏  ›  技术社区  ›  yome

用R求1和0矩阵的热图

  •  1
  • yome  · 技术社区  · 7 年前

    下面是我的示例数据,基本上是一个以行名为人名的矩阵 以及每行的一些列。数据中只有0和1。我想用热图将其可视化。(红色表示0秒,绿色表示1秒或任何其他颜色编码)。我如何使用R实现这一点?您可以向我展示使用任何只包含1和0(二进制值)的示例数据集。

    enter image description here

    3 回复  |  直到 7 年前
        1
  •  2
  •   Bussller Junior Vieira    7 年前

    只是使用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

        2
  •  0
  •   jyjek    7 年前

    具有 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 更新: 您可以添加 hc_size(height = 800) 高度=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

        3
  •  0
  •   Bussller Junior Vieira    7 年前

    此答案使用 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简单得多。

    希望这有帮助!