【问题标题】:Grid plot of missing data缺失数据的网格图
【发布时间】:2019-05-21 08:36:20
【问题描述】:

我的数据如下所示:

Col1 Var1 Var2
A     1    NA
B     NA    1
C     1    NA
D     1    1

我想创建一个缺失数据的网格图,就像使用 Amelia 包 (https://www.r-bloggers.com/ggplot-your-missing-data-2/) 所做的那样

但是,我发现结果很丑。基本上,我希望 col 1 中的变量位于 x 轴上,而 Var1 和 Va2 位于 Y 轴上。存在时呈灰色,不存在时呈黑色。这有意义吗?

有什么建议吗?我把阿米莉亚图放在下面

【问题讨论】:

    标签: r plot missing-data


    【解决方案1】:

    这是一个ggplot2 选项。

    首先将您的数据从宽调整为长,然后将 ǸA 替换为 0s(或任何其他值)。

    df1_long <- tidyr::gather(replace(df1, is.na(df1), 0), key, value, -Col1)
    

    现在绘图

    library(ggplot)
    ggplot(df1_long, aes(Col1, key, fill = factor(value))) +
      geom_tile() + 
      scale_x_discrete(expand = c(0, 0)) +
      scale_y_discrete(expand = c(0, 0)) +
      scale_fill_manual(values = c(`0` = "black",
                                   `1` = "grey80"),
                        labels = c("Missing", "Observed")) +
      labs(title = "Your Title",
           fill = NULL,
           x = NULL,
           y = NULL) +
      coord_equal() +
      theme(legend.position = "bottom")
    

    数据

    df1 <- structure(list(Col1 = c("A", "B", "C", "D"), Var1 = c(1L, NA, 
    1L, 1L), Var2 = c(NA, 1L, NA, 1L)), .Names = c("Col1", "Var1", 
    "Var2"), class = "data.frame", row.names = c(NA, -4L))
    

    【讨论】:

      【解决方案2】:

      基础 R 解决方案

      Dat = t(matrix(as.numeric(is.na(df[,2:3])), nrow=nrow(df)))
      rownames(Dat) = names(df)[2:3]
      colnames(Dat) = df$Col1
      
      heatmap(Dat, NA, NA, scale="none", col=c("gray", "black"))
      

      数据

      df = read.table(text="Col1 Var1 Var2
      A     1    NA
      B     NA    1
      C     1    NA
      D     1    1", 
      header=TRUE)
      

      【讨论】:

      • 效果很好!谢谢!
      猜你喜欢
      • 1970-01-01
      • 2015-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-02
      • 2013-12-08
      • 1970-01-01
      相关资源
      最近更新 更多