dplyr/ggplot2:带有包含 na 值的堆叠条的时间图

dplyr/ggplot2: time plot with stacked bars containing na values

如何使用 dplyr 和 ggplot2 制作包含 na 值的堆叠条形图?

x轴:年
Y 轴:观察数和 NA 数

data <- data.frame(year = c(2015, 2015, 2016, 2016),
                     column2 = c(4, NA, 9, 1))


library (dplyr)

missing_data <- data %>%
                   count(year, complete.cases(column2))

我的成绩

year    complete.cases(column2)     n
(dbl)                      (lgl) (int)
1  2015                   FALSE     1
2  2015                    TRUE     1
3  2016                    TRUE     2

我尝试了什么:

library(ggplot2)
na_plot  <- ggplot (missing_data, aes(x=year, y=n))  
na_plot+
geom_bar(stat="identity", aes(fill = complete.cases(column2))

我认为函数 complete.cases 以某种方式干扰了变量名。尝试重命名(也 factor year):

data <- data.frame(year = c(2015, 2015, 2016, 2016),
                   column2 = c(4, NA, 9, 1))

library(dplyr)
library(ggplot2)

missing_data <- data %>%
   count(year, complete.cases(column2))

names(missing_data)[2] = "col2"   

na_plot <- ggplot(missing_data, aes(x=factor(year), y=n))
na_plot + geom_bar(stat="identity", aes(fill = col2))