How to add frequency count labels to the bars in a bar graph using ggplot2? [duplicate]
Asked Answered
K

1

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

Kagu answered 24/10, 2014 at 17:55 Comment(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 numbersLibertinage
D
122
ggplot(data=diamonds, aes(x=clarity)) +
geom_bar() +
geom_text(stat='count', aes(label=..count..), vjust=-1)

enter image description here

Disencumber answered 24/10, 2014 at 20:58 Comment(7)
For me, it worked with stat='count'Dandridge
Stat = "count" worked for me as well. The error says StatBin requires a continuous variable, but I have categorical variables.Wyck
What is you use the "fill = variable" option, and only want the total count over the bars?Downright
I get this warning: stat_bin() using bins = 30. Pick better value with binwidth.Mashie
I got an error saying "stat_count requires the following missing aesthetics: x"Biafra
ggplot2 version 3.3.0 now supports geom_text(stat = "count", aes(label = after_stat(count)), vjust = -1)Hexone
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...Dutiable

© 2022 - 2024 — McMap. All rights reserved.