46

Consider the following lines.

p <- ggplot(mpg, aes(x=factor(cyl), y=..count..))

p + geom_histogram()   
p + stat_summary(fun.y=identity, geom='bar')

In theory, the last two should produce the same plot. In practice, stat_summary fails and complains that the required y aesthetic is missing.

Why can't I use ..count.. in stat_summary? I can't find anywhere in the docs information about how to use these variables.

Ernest A
  • 7,196
  • 8
  • 33
  • 39
  • 5
    Those variables are returned by `stat_bin` which is called by `geom_histogram`, but not by `stat_summary` (since you're supposed to be supplying your own stat), hence the variables aren't available. – joran Jan 28 '13 at 20:16

1 Answers1

57

Expanding @joran's comment, the special variables in ggplot with double periods around them (..count.., ..density.., etc.) are returned by a stat transformation of the original data set. Those particular ones are returned by stat_bin which is implicitly called by geom_histogram (note in the documentation that the default value of the stat argument is "bin"). Your second example calls a different stat function which does not create a variable named ..count... You can get the same graph with

p + geom_bar(stat="bin")

In newer versions of ggplot2, one can also use the stat function instead of the enclosing .., so aes(y = ..count..) becomes aes(y = stat(count)).

Axeman
  • 29,327
  • 7
  • 77
  • 89
Brian Diggs
  • 55,682
  • 13
  • 158
  • 183
  • 3
    I'd like to perform an arithmetic operation (in this case, addition) between `..count..` variable and a user-defined variable (I've done it with constants). Unfortunately, `ggplot2` doesn't recognize the variable's name and produces an error. Any ideas, Brian? – Aleksandr Blekh Oct 14 '14 at 08:13
  • 2
    @AleksandrBlekh That should be a new question, not a comment to the answer of an old question. Offhand, I don't think it is possible. A variable in your primary data.frame would have more values than the transformed `..count..` variable, so there would be no way to match them up. Without more detail and a reproducible example (e.g. a new question), I can't answer for sure, though. – Brian Diggs Oct 14 '14 at 15:37
  • Fair enough! I thought that this question is too "small" and not worth a separate posting. I've already figured that it's not possible, your comment additionally confirms that. Thank you! – Aleksandr Blekh Oct 14 '14 at 23:30
  • 1
    I really wish geom_bar generated the ..density.. variable like its cousin function geom_histogram does. – aaiezza Dec 13 '16 at 16:29