2

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 total, but can't figure out how to add the percents total on top of the bars. I'm trying to use geom_text, but not able to get it work.

A minimal example:

iris %>% 
  group_by(Species) %>% 
  summarize(count = n()) %>% 
  mutate(percent = count/sum(count)) %>% 
  ggplot(aes(x=Species, y=count)) +
    geom_bar(stat="identity") + 
    geom_text(aes(label = scales::percent(..prop..), y=..count..), stat= "count", vjust = -.5)

I have looked at other answers like How to add percentage or count labels above percentage bar plot?, but in those examples, both the y axis and labels show percents. I am trying to show counts on the y axis and percents in the labels.

Harry M
  • 1,848
  • 3
  • 21
  • 37
  • Have you seen [this question](https://stackoverflow.com/questions/29869862/how-to-add-percentage-or-count-labels-above-percentage-bar-plot), for example? – jazzurro May 25 '18 at 01:32
  • 1
    Possible duplicate of [How to add percentage or count labels above percentage bar plot?](https://stackoverflow.com/questions/29869862/how-to-add-percentage-or-count-labels-above-percentage-bar-plot) – Matias Andina May 25 '18 at 01:34
  • yes, I have seen those, but those show percent on both the y axis and the labels. I'm looking for counts on the y axis and percents on the labels. – Harry M May 25 '18 at 01:35

2 Answers2

4

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)

enter image description here

hpesoj626
  • 3,529
  • 1
  • 17
  • 25
1
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))
d.b
  • 32,245
  • 6
  • 36
  • 77