8

I am working my way through The R Graphics Cookbook and ran into this set of code:

library(gcookbook)
library(ggplot2)

p <- ggplot(faithful, aes(x = eruptions, y = waiting)) + 
   geom_point() +
   stat_density2d(aes(alpha=..density.., fill=..density..), geom="tile", contour=FALSE)

It runs fine, but I don't understand what the .. before and after density is referring to. I can't seem to find it mentioned in the book either.

Anton
  • 4,765
  • 12
  • 36
  • 50
  • 2
    `..density..`, `..count..` and others refer to variables that have been created on-the-fly by ggtplo2 using a stat_xxx function. http://stackoverflow.com/questions/14570293/special-variables-in-ggplot-count-density-etc – baptiste Dec 18 '13 at 16:25

1 Answers1

6

Variable names beginning with .. are possible in R, and are treated in the same way as any other variable. Trying creating one of your own.

..x.. <- 1:5

ggplot2 often creates appends extra columns to your data frame in order to draw the plot. (In ggplot2 terminology, this is "fortifying the data".) ggplot2 uses the naming convention ..something.. for these fortified columns.

This is partly because using ..something.. is unlikely to clash with existing variables in your dataset. Take that as a hint that you shouldn't name the columns in your dataset using that pattern.

The stat_density* functions use ..density.. to represent the density of the x variable. Other fortified variable names include ..count...

Richie Cotton
  • 118,240
  • 47
  • 247
  • 360
  • I thin instead that is more of a flag to choose a variable named "density" in a local data.frame created by `?stat_bin`. One can even use the variables `density` or `counts`, but attempts to use a variable named `..density..` would fail. – IRTFM Dec 18 '13 at 17:09
  • @DWin I've completely rewritten the answer so that it is no longer garbled nonsense. – Richie Cotton Dec 18 '13 at 17:20
  • Except according to the ?stat_bin page (and my limited experience), the actual names are `density` , `count`, `ncount` and `ndensity`. I do agree that the choice of the spelling for the "fortification" flag was to avoid collision with user names. – IRTFM Dec 18 '13 at 17:25