Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 750
Tamer Koksal Avatar asked Oct 24 '14 17:10

Tamer Koksal


People also ask

How do I add labels to a bar chart in R?

To add labels on top of each bar in Barplot in R we use the geom_text() function of the ggplot2 package. Parameters: value: value field of which labels have to display. nudge_y: distance shift in the vertical direction for the label.

What is stat count in Ggplot?

By default, geom_bar uses stat="count" which makes the height of the bar proportion to the number of cases in each group (or if the weight aethetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use stat="identity" and map a variable to the y aesthetic.

What is Geom_bar stat?

geom_bar() makes the height of the bar proportional to the number of cases in each group (or if the weight aesthetic is supplied, the sum of the weights).


1 Answers

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

enter image description here

like image 120
keegan Avatar answered Sep 27 '22 23:09

keegan