通过 ggplot2 在条形图顶部添加来自另一个数据集的注释

Add annotation from another data set at the top of bar plot by ggplot2

我用下面的 R 代码创建了一个 ggplot。我想将数据集评估中的注释添加到条形图中。注释应该出现在每所学校的栏的顶部。比如A学校,第一个注解应该是good,第二个注解应该是open,第二个注解在第一个注解下面。我尝试了 gem_text,但没有成功。

school <- c("A","A","A","B","B","B","C","C","C")
satisify <- c("yes","yes","no","no","no","yes","no","no","yes")
evaluate <-as.data.frame(cbind(c("A","B","C"),c("good","terrible","terrible"),c("open","close","close")))
colnames(evaluate) <- c("school","evaluate","decision")

data <- as.data.frame(cbind(school, satisify))
library(ggplot2)
ggplot(data,aes(x=school,fill=satisify))+geom_bar(aes(group=satisify, y=..prop..),position="dodge")

也许,这是一个非常复杂但有效的方法(?)。

library(tidyverse)

data %>%
  count(school, satisify) %>%
  group_by(satisify) %>%
  mutate(n = prop.table(n)) %>%
  ungroup %>%
  left_join(evaluate, by = 'school') %>%
  pivot_longer(cols = c(evaluate, decision)) %>%
  group_by(school) %>%
  slice(1, n()) %>%
  ggplot(aes(x=school, y= n, fill=satisify, group = satisify, label = value)) + 
  geom_col(position = 'dodge') + 
  geom_text(position = position_dodge(width = 0.9), vjust = -0.5)

这是你想要的吗?

library(tidyverse)
data %>%
  count(satisify, school) %>%
  group_by(satisify) %>%
  mutate(prop = n / sum(n)) %>%
  ungroup() %>%
  left_join(evaluate) %>%
  ggplot(aes(school, prop, fill = satisify, group = satisify)) + 
  geom_col(position = position_dodge()) +
  geom_text(aes(label = evaluate), position = position_dodge(width = 0.9), vjust = -0.3) +
  geom_text(aes(label = decision), position = position_dodge(width = 0.9), vjust = 1.3)