How to add frequency count labels to the bars in a bar graph using ggplot2?

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

enter image description here

Share:
99,462

Related videos on Youtube

Tamer Koksal
Author by

Tamer Koksal

Updated on March 25, 2020

Comments

  • Tamer Koksal
    Tamer Koksal about 4 years

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

    • lawyeR
      lawyeR over 9 years
      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
  • Dinesh
    Dinesh over 7 years
    For me, it worked with stat='count'
  • Alison Bennett
    Alison Bennett about 7 years
    Stat = "count" worked for me as well. The error says StatBin requires a continuous variable, but I have categorical variables.
  • Esben Eickhardt
    Esben Eickhardt about 7 years
    What is you use the "fill = variable" option, and only want the total count over the bars?
  • skan
    skan over 6 years
    I get this warning: stat_bin() using bins = 30. Pick better value with binwidth.
  • Sagar
    Sagar over 4 years
    I got an error saying "stat_count requires the following missing aesthetics: x"
  • gofraidh
    gofraidh about 4 years
    ggplot2 version 3.3.0 now supports geom_text(stat = "count", aes(label = after_stat(count)), vjust = -1)
  • RTD
    RTD over 3 years
    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...