将计数标签添加到比例图

Add count lable to proportion plot

我正在尝试将计数标签添加到比例图中。这是我的数据示例和到目前为止我完成的代码。

df <- data.frame(E2A = c(1, 1, 2, 2, 1, 1, 2, 1, 2, NA),
                 E4A = c("P", "P", "P", NA, "G", "G", "H", "H", "H", "H"),
                 E5A = c("R", "R", "R", "R", "R", "O", "O", "O", "O", "O"),
                 Tooth = c(rep("P3", 9), NA))

ggplot(data = remove_missing(df, na.rm = TRUE, vars = c("E2A", "E4A", "E5A"))) + # remove NA's for cleaner plot
  aes(x = E4A, fill = E5A) +
  geom_bar(position = "fill") +
  theme(plot.title = element_text(hjust = 0.5)) +
  labs(x = "", y = "", fill = "Canal configurations") +
  theme_bw(base_size = 14) +
  theme(legend.position = "top") +
  theme(axis.text.y = element_text(size = 8)) +
  theme(axis.text.x = element_text(size = 10)) +
  guides(fill = guide_legend(nrow = 1, byrow = TRUE)) +
  facet_wrap(.~ E2A, labeller = labeller(E2A = E2_lab), scales = "free")

有没有办法向堆叠条形图添加计数标签?下面是一个模型,以帮助形象化我正在尝试做的事情。

我们可以在 geom_label 中使用 stat = 'count' 得到:

ggplot(data = remove_missing(df, na.rm = TRUE, vars = c("E2A", "E4A", "E5A"))) + # remove NA's for cleaner plot
  aes(x = E4A, fill = E5A) +
  geom_bar(position = "fill") +
  geom_label(stat = 'count', aes(label = ..count..), position = position_fill(vjust = 0.5)) +
  theme(plot.title = element_text(hjust = 0.5)) +
  labs(x = "", y = "", fill = "Canal configurations") +
  theme_bw(base_size = 14) +
  theme(legend.position = "top") +
  theme(axis.text.y = element_text(size = 8)) +
  theme(axis.text.x = element_text(size = 10)) +
  guides(fill = guide_legend(nrow = 1, byrow = TRUE)) +
  facet_wrap(.~ E2A, scales = "free")

我们可以这样使用geom_label

ggplot(data = remove_missing(df, na.rm = TRUE, vars = c("E2A", "E4A", "E5A"))) + # remove NA's for cleaner plot
  aes(x = E4A, fill = E5A) +
  geom_bar(position = "fill") +
  theme(plot.title = element_text(hjust = 0.5)) +
  labs(x = "", y = "", fill = "Canal configurations") +
  theme_bw(base_size = 14) +
  theme(legend.position = "top") +
  theme(axis.text.y = element_text(size = 8)) +
  theme(axis.text.x = element_text(size = 10)) +
  guides(fill = guide_legend(nrow = 1, byrow = TRUE)) +
  facet_wrap(.~ E2A, scales = "free") +
  geom_label(data = . %>% 
              count(E2A, E4A, E5A, Tooth),
            aes(y = n, label = n),size=5,
            position = position_fill(0.5),
            show.legend = FALSE)