37

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...

Tamer Koksal
  • 393
  • 1
  • 3
  • 5
  • 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 '14 at 20:02

1 Answers1

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

enter image description here

Jordan
  • 365
  • 1
  • 10
keegan
  • 2,892
  • 1
  • 17
  • 20
  • 12
    For me, it worked with `stat='count'` – Dinesh Dec 19 '16 at 20:17
  • 1
    `Stat = "count"` worked for me as well. The error says `StatBin` requires a continuous variable, but I have categorical variables. – Alison Bennett Feb 28 '17 at 04:21
  • What is you use the "fill = variable" option, and only want the total count over the bars? – Esben Eickhardt Mar 23 '17 at 09:47
  • 1
    I get this warning: `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. – skan Oct 28 '17 at 01:44
  • 1
    I got an error saying "stat_count requires the following missing aesthetics: x" – Sagar Jan 17 '20 at 00:25
  • 6
    ggplot2 version 3.3.0 now supports `geom_text(stat = "count", aes(label = after_stat(count)), vjust = -1)` – gofraidh Apr 06 '20 at 11:40
  • If you want to use `geom_label`: `geom_label(stat="count", aes(label=format(after_stat(count), big.mark = ",")))`. I don't know if this calculates the counts twice, once for `geom_bar` and once for the labels... – Rafs Oct 16 '20 at 13:31