如何通过位置箱绘制 NA 的所有出现

How to graph all the occurences of NA by bins of positions

我对 R 有点陌生,我希望将所有出现的 NA 随位置变化绘制成直方图。我开始使用 ggplot 但我不确定从哪里开始?

df <- data.frame(position=c(3, 5, 6, 7, 16, 17, 19, 20, 21, 35, 46, 78, 98, 100, 
                            145, 146, 147), 
                 petal15=c(0, 1, 1, 1, 0, NA, 1, NA, NA, NA, 1, 0, 0, 1, NA, 
                           0, NA), 
                 petal20=c(1, 0, 0, 1, 1, 1, 1, 1, NA, NA, 1, 1, NA, NA, 0, 
                           0, 0))

如果我理解正确的话,你正在找这个。

hist(rowSums(is.na(df)), xlab='occurrences', col=4, main="NA's")

编辑

为了在评论中实现您的想法,我们首先需要一份职位列表。

(pos <- lapply((0:14)*10 + 1, \(x) (0:9) + x))
# [[1]]
# [1]  1  2  3  4  5  6  7  8  9 10
# 
# [[2]]
# [1] 11 12 13 14 15 16 17 18 19 20
#
# [...]
#
# [[15]]
# [1] 141 142 143 144 145 146 147 148 149 150

我们使用 sapply 创建所需的矩阵并将其通过管道传输到 barplot()

sapply(pos, \(i) colSums(is.na(df[df$position %in% i, -1]))) |>
  barplot(beside=TRUE, xlim=c(1, 48), ylim=c(0, 2.5), col=3:4,
          xlab='Occurences', ylab='Freq', main="NA's",
          legend.text=names(df[-1]), args.legend=list(x='topright'),
          names.arg=Reduce(\(x, y) paste0(x, '-', y), 
                           as.data.frame(t(sapply(pos, range)))),
          cex.names=.8) 
box()

注:

R.version.string
# [1] "R version 4.1.2 (2021-11-01)"

数据:

df <- structure(list(position = c(3, 5, 6, 7, 16, 17, 19, 20, 21, 35, 
46, 78, 98, 100, 145, 146, 147), petal15 = c(0, 1, 1, 1, 0, NA, 
1, NA, NA, NA, 1, 0, 0, 1, NA, 0, NA), petal20 = c(1, 0, 0, 1, 
1, 1, 1, 1, NA, NA, 1, 1, NA, NA, 0, 0, 0)), class = "data.frame", row.names = c(NA, 
-17L))

Tidyverse 解决方案 - 旋转更长的时间,然后过滤所有 NA,然后按照上面的建议绘制直方图,但改为使用 ggplot。

library(tidyverse)

df_na <- 
  df %>%
  pivot_longer(-position) %>%
  filter(is.na(value)) 
  
ggplot(df_na, aes(position, fill = name)) +
  geom_histogram(binwidth = 5, position = position_dodge()) +
  scale_x_continuous(breaks = seq(0,150,10))

reprex package (v2.0.1)

于 2021-12-19 创建