draw the sum value above the stacked bar in ggplot2

前端 未结 2 1496
囚心锁ツ
囚心锁ツ 2020-11-27 21:49

How do I draw the sum value of each class (in my case: a=450, b=150, c=290, d=90) above the stacked bar in ggplot2? Here is my code:

#Data
hp=read.csv(textCo         


        
相关标签:
2条回答
  • 2020-11-27 22:11

    You can use the built-in summary functionality of ggplot2 directly:

    ggplot(hp, aes(reorder(class, -amount, sum), amount, fill = year)) +
      geom_col() +
      geom_text(
        aes(label = stat(y), group = class), 
        stat = 'summary', fun = sum, vjust = -1
      )
    

    0 讨论(0)
  • 2020-11-27 22:17

    You can do this by creating a dataset of per-class totals (this can be done multiple ways but I prefer dplyr):

    library(dplyr)
    totals <- hp %>%
        group_by(class) %>%
        summarize(total = sum(value))
    

    Then adding a geom_text layer to your plot, using totals as the dataset:

    p + geom_bar(binwidth = 0.5, stat="identity") +  
        aes(x = reorder(class, -value, sum), y = value, label = value, fill = year) +
        theme() +
        geom_text(aes(class, total, label = total, fill = NULL), data = totals)
    

    You can make the text higher or lower than the top of the bars using the vjust argument, or just by adding some value to total:

    p + geom_bar(binwidth = 0.5, stat = "identity") +  
        aes(x = reorder(class, -value, sum), y = value, label = value, fill = year) +
        theme() +
        geom_text(aes(class, total + 20, label = total, fill = NULL), data = totals)
    

    enter image description here

    0 讨论(0)
提交回复
热议问题