42

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?

tonytonov
  • 25,060
  • 16
  • 82
  • 98
Remi.b
  • 17,389
  • 28
  • 87
  • 168

2 Answers2

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)
Community
  • 1
  • 1
tonytonov
  • 25,060
  • 16
  • 82
  • 98
22

now ..prop.. is available

ggplot(data=tips, aes(x=day)) + 
  geom_bar(aes(y = ..prop.., group = 1))
Dambo
  • 3,318
  • 5
  • 30
  • 79
  • 1
    This works if you are using facets, while the `..count..` option does not! – r_alanb Jul 19 '18 at 17:51
  • @r_alanb do you mean adding e.g. `facet_wrap(~sex)`? It works with both for me. – Dambo Jul 23 '18 at 10:31
  • 1
    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. – r_alanb Jul 25 '18 at 00:06
  • @r_alanb `..count../sum(..count..)` and `..prop` work exactly the same for me as long as you set `group = 1` – Dambo Jul 25 '18 at 09:17
  • `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. – r_alanb Jul 26 '18 at 02:34