Display frequency instead of count with geom_bar() in ggplot
Asked Answered
S

3

43

On this page, they give the following example

library(ggplot2)
library(reshape2)
ggplot(data=tips, aes(x=day)) + geom_bar(stat="bin")

Instead of a count I'd like to have a frequency in y-axis. How can I achieve this?

Salado answered 7/11, 2013 at 12:29 Comment(0)
E
57

Here's the solution which can be found in related question:

pp <- ggplot(data=tips, aes(x=day)) + 
      geom_bar(aes(y = (..count..)/sum(..count..)))

If you would like to label frequencies as percentage, add this (see here):

library(scales)
pp + scale_y_continuous(labels = percent)
Endoblast answered 8/11, 2013 at 7:30 Comment(6)
What is the meaning of the dot-dot notation in ..count..? Do you have any reference to that?Individualize
@Individualize Take a look at this question.Endoblast
How would you obtain data labels for the frequencies, to be shown above each bar?Marmalade
I really wish geom_bar generated the ..density.. variable like its cousin function geom_histogram does.Dichlamydeous
I think think labels=percent in scale_y_continuous(labels = percent) doesnt work anymoreLilylilyan
@Lilylilyan Running on ggplot2_3.1.0, scales_1.0.0 is still fine (R 3.5.1, Win 10).Endoblast
A
23

now ..prop.. is available

ggplot(data=tips, aes(x=day)) + 
  geom_bar(aes(y = ..prop.., group = 1))
Atavism answered 19/3, 2018 at 20:49 Comment(5)
This works if you are using facets, while the ..count.. option does not!Shudder
@Shudder do you mean adding e.g. facet_wrap(~sex)? It works with both for me.Atavism
I should have defined "works". It will create a figure if you use ..count../sum(..count..), but the frequency will sum to 1 over all of the facets (I think). If you use ..prop.., the frequency will sum to 1 in each facet. Maybe it depends on what you're trying to show.Shudder
@Shudder ..count../sum(..count..) and ..prop work exactly the same for me as long as you set group = 1Atavism
ggplot(data=tips, aes(x=day)) + geom_bar(aes(y = ..prop.., group = 1)) + facet_wrap(~sex) and ggplot(data=tips, aes(x=day)) + geom_bar(aes(y = (..count..)/sum(..count..), group = 1)) + facet_wrap(~sex) do not yield the same plot for me. You can also remove group=1 in the ..count.. version and it looks the same.Shudder
S
3

With ggplot2 >= 3.4.0, I think the recommended way is the following:

library("ggplot2")
library("reshape2")

ggplot(data = tips, aes(x = day)) + 
  geom_bar(aes(y = after_stat(prop), group = 1))
Sot answered 26/12, 2023 at 15:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.