使用 ggplot 和 r 报告条形图中 NA 的数量

Reporting number of NAs in Bar Plot using ggplot and r

目标

我正在尝试创建一系列条形图,以显示对最近在 6 个国家/地区举行的选举的满意度。数据包括 NA,我想在各自的条形图中报告每个国家/地区的 NA 数量。

有没有办法让 ggplot / R 自动在条形图中插入 NA 个值?我似乎无法自己解决这个问题。我在每个图表中都放置了占位符文本:"NA = ##".

谢谢!

数据结构

数据如下所示:

Country     Satisfaction
-------     ------------
Algeria     1
Algeria     3
Algeria     NA
...
Burundi     3
Burundi     2
Burundi     2
...
Cameroon    4
Cameroon    NA
Cameroon    NA
...

示例代码

countries <- c("Algeria", "Benin", "Botswana", "Burkina Faso", "Burundi", "Cameroon")
countryvar <- rep(countries, each = 30)
satisfaction <- sample(1:5, 180, replace=TRUE, prob=c(0.2, 0.3, 0.35, 0.1, 0.05))
satisfaction[satisfaction==5] <- NA
df <- as.data.frame(cbind(countryvar, satisfaction))

p <- ggplot2::ggplot(data = subset(df, !is.na(satisfaction)), aes(satisfaction))
p + 
  geom_bar(aes(fill = satisfaction)) + 
  facet_wrap(~ countryvar, nrow = 2) + 
  labs(x = "Satisfaction with Recent Election", y = "Counts") + 
  annotate("rect", xmin = 3.5, xmax = 4.5, ymin = 22.5, ymax = 25, fill = "white", colour = "black") + 
  annotate("text", x = 3.6, y = 23.1, hjust = 0, vjust = 0, label = "NA = ##") +
  scale_fill_manual(values = c("snow3", "seashell3", "snow4", "black"))  +
  theme_bw()

这是一种使用 geom_text 的方法。

基本上每个国家 NA

subset(df, is.na(satisfaction))%>%
                 count(countryvar)

并将其用作 geom_text

的数据
library(ggplot2)
library(tidyverse)

p <- ggplot2::ggplot(data = subset(df, !is.na(satisfaction)), aes(satisfaction))
p + 
  geom_bar(aes(fill = satisfaction)) + 
  facet_wrap(~ countryvar, nrow = 2) + 
  labs(x = "Satisfaction with Recent Election", y = "Counts") + 
  annotate("rect", xmin = 3.5, xmax = 4.5, ymin = 22.5, ymax = 25, fill = "white", colour = "black") + 
  geom_text(data = subset(df, is.na(satisfaction))%>%
             count(countryvar), x = 3.6, y = 23.1, hjust = 0, vjust = 0, aes(label = paste("NA = ", n))) +
  scale_fill_manual(values = c("snow3", "seashell3", "snow4", "black"))  +
  theme_bw()