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

使用ggplot2热图直观显示每列中的NAs数量

  •  0
  • Kots  · 技术社区  · 7 年前

    我有一个向量,它保存数据集每列中的NAs数量。

    countNA <-  c(0, 0, 88, 88, 161, 84, 540, 0, 84, 84, 84, 86, 101, 77, 80, 80, 72, 119, 72, 0, 72, 86, 72, 70, 70, 70, 161, 86, 80, 101, 77, 497, 80, 161, 88, 84, 86, 497, 471, 81, 560, 88, 88, 497, 472, 84, 0)
    

    我想在ggplot2中将其绘制为热图

    countNA <-  c(0, 0, 88, 88, 161, 84, 540, 0, 84, 84, 84, 86, 101, 77, 80, 80, 72, 119, 72, 0, 72, 86, 72, 70, 70, 70, 161, 86, 80, 101, 77, 497, 80, 161, 88, 84, 86, 497, 471, 81, 560, 88, 88, 497, 472, 84, 0)
    plotNA3 <- as.data.frame(countNA, row.names = NULL)
    plotNA3$VariableNames <- as.factor(seq(1, length(countNA)))
    plotNA3$team <- as.factor(rep(1, length(countNA)))
    
    ggplot(data = plotNA3, aes(x=VariableNames, y=team, fill=countNA)) +
      geom_tile() +
      labs(fill='Number of NAs in each column')+
      geom_text(aes(label=paste(sprintf("%.1d", countNA))), size=2, color="white")
    

    但是,如果运行此操作,您将看到,它不是一块方形瓷砖,而是拉伸的。是否可以稍微更改它,使y轴不拉伸?

    我猜真正的问题是“如何创建只有1个变量的热图”

    1 回复  |  直到 7 年前
        1
  •  1
  •   Marco Sandri    7 年前

    以下是一个可能的解决方案:

    ggplot(data = plotNA3, aes(x=VariableNames, y=team, fill=countNA)) +
      geom_tile() +
      labs(fill='Number of NAs in each column')+
      geom_text(aes(label=paste(sprintf("%.1d", countNA))), size=2, color="white")+
      theme(aspect.ratio=1/25)
    

    enter image description here