在每个栏的顶部添加总计

Add totals on top of each bar

我正在绘制我的数据,并希望在每个条形图的顶部显示总计,但是一旦我添加总数,条形图就会消失。

long<- data.frame(
            Name = c("abc","abc","abc","gif","gif","gif","xyz","xyz","xyz"),
            variable = c("a","b","c","a","b","c","c","b","a"),
            value = c(4,6,NA,2,8,1,6,NA,NA))

代码

p<-long %>%
  ggplot() + aes(Name, value, fill=variable) +
  geom_bar(stat="summary", position = "fill") +
  scale_y_continuous(labels = scales::percent_format()) +
  ylab("Total_num") +
  ggtitle("Totalnum") +
  theme(plot.title = element_text(size = 20, hjust = 0.5)) +
  theme(axis.text.x = element_text(angle = 75, vjust = 0.95, hjust=1))
  p+ stat_summary(fun.y = sum, aes(label = ..y.., group = Name)+
geom_text(stat='value', aes(group=Name, label=.."value"..), position = position_stack(vjust = 0.5))

您可以实现用每个名称的总和创建另一个 df 并将其传递给 geom_text()

long<- data.frame(
      Name = c("abc","abc","abc","gif","gif","gif","xyz","xyz","xyz"),
      variable = c("a","b","c","a","b","c","c","b","a"),
      value = c(4,6,NA,2,8,1,6,NA,NA))
    
    
long_totals <- long %>%
      group_by(Name) %>%
      summarise(Total = sum(value, na.rm = T))
    
    p <- ggplot()+
      geom_bar(data = long,
               aes(x = Name, 
                   y = value,
                   fill=variable),
               stat="summary", 
               position = "fill") +
      geom_text(data = long_totals,
                aes(y = 100,
                    x = Name,
                    label = Total),
                size = 7,
                position = position_fill(vjust = 1.02)) +
      scale_y_continuous(labels = scales::percent_format()) +
      ylab("Total_num") +
      ggtitle("Totalnum") +
      theme(plot.title = element_text(size = 20, hjust = 0.5)) +
      theme(axis.text.x = element_text(angle = 75, vjust = 0.95, hjust=1))