39

I want to plot frequency distribution of an [r] factor variable as a bargraph, where bars represent the frequency counts of the factor levels. I use ggplot2 to do that and there's no problem with that.

What I can't figure out is how to add frequency count labels to the bars in the bargraph. The syntax that I've tried is as follows:

ggplot(data, aes(x = factorvar)) + geom_bar(fill = "somecolor") + geom_text(aes(y = ???))

I think I thoroughly searched in stackoverflow and "R Graphics Cookbook" by W.Chang but I couldn't find any specific answer to what parameter should I match to "y" in the aesthetics of geom_text() above. I tried some variants like: (y = ..count..) but it didn't work.

I would appreciate any help. Thanks...

1
  • From some partial notes for this question, the example given was geom_text(aes(label = numbers), vjust=-1, position = position_dodge(0.9), size = 3) # try numbers
    – lawyeR
    Oct 24, 2014 at 20:02

1 Answer 1

119
ggplot(data=diamonds, aes(x=clarity)) +
geom_bar() +
geom_text(stat='count', aes(label=..count..), vjust=-1)

enter image description here

7
  • 12
    For me, it worked with stat='count'
    – Dinesh
    Dec 19, 2016 at 20:17
  • 1
    Stat = "count" worked for me as well. The error says StatBin requires a continuous variable, but I have categorical variables. Feb 28, 2017 at 4:21
  • 1
    I get this warning: stat_bin() using bins = 30. Pick better value with binwidth.
    – skan
    Oct 28, 2017 at 1:44
  • 1
    I got an error saying "stat_count requires the following missing aesthetics: x"
    – Sagar
    Jan 17, 2020 at 0:25
  • 6
    ggplot2 version 3.3.0 now supports geom_text(stat = "count", aes(label = after_stat(count)), vjust = -1)
    – gofraidh
    Apr 6, 2020 at 11:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.