缺失数据的网格图

Grid plot of missing data

我的数据是这样的:

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 轴上。存在时像灰色,不存在时像黑色。这有意义吗?

有什么建议吗?我把 Amelia 图放在下面

这里有一个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))

基础 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)