Show percent of total on top of geom_bar in ggplot2 while showing counts on y axis

前端 未结 2 352
庸人自扰
庸人自扰 2021-01-15 01:37

I\'m trying to create a bar plot with ggplot2, showing counts on the y axis, but also the percents of total on top of each bar. I\'ve calculated the counts and percents of t

相关标签:
2条回答
  • 2021-01-15 02:19

    Just use percent as label.

    iris %>% 
      group_by(Species) %>% 
      summarize(count = n()) %>% 
      mutate(percent = count/sum(count)) %>% 
      ggplot(aes(x=Species, y=count)) +
      geom_col() +
      geom_text(aes(label = paste0(round(100 * percent, 1), "%")), vjust = -0.25)
    

    0 讨论(0)
  • 2021-01-15 02:30
    library(dplyr)
    library(ggplot2)
    df1 = iris %>% 
        group_by(Species) %>% 
        summarize(count = n()) %>% 
        mutate(percent = count/sum(count))
    ggplot(data = df1, aes(x = Species, y = count, label = paste0(round(percent,2),"%"))) +
        geom_bar(stat="identity") +
        geom_text(aes(y = count*1.1))
    
    0 讨论(0)
提交回复
热议问题