title: (ggplot) in stat_density, aes sometimes does not map variables from default dataset
body: <p>Trying to understand how ggplot mapping works…</p>
  
  <p>Consider data table dt with two columns:</p>
  
  <pre><code>group:  data grouping variable [a, b, … e]
  values: the data [here, N(x,1) where x depends on group]
  </code></pre>
  
  <p>The following generates a sample dataset.</p>
  
  <pre><code>library(data.table)
  set.seed(333)
  dt  &lt;- data.table(group=rep(letters[1:5],each=20))
  dt[,values:=rnorm(100,mean=as.numeric(factor(group)))]
  </code></pre>
  
  <p>The following generates density plots for each group scaled to (0,1).</p>
  
  <pre><code>ggp &lt;- ggplot(dt)      # establish dt as the default dataset
  ggp + stat_density(aes(x=values, color=group, y=..scaled..), 
                     geom="line", position="identity")
  </code></pre>
  
  <p>The following generates density plots with scale changed from (0,1) to (-25,+25).</p>
  
  <pre><code>ggp + stat_density(aes(x=values, color=group, y=-25+50*..scaled..), 
                     geom="line", position="identity")
  </code></pre>
  
  <p>But the following generates and error:</p>
  
  <pre><code>ggp + stat_density(aes(x=values, color=group, y=min(values)+diff(range(values))*..scaled..), 
                     geom="line", position="identity")
  Error in eval(expr, envir, enclos) : object 'values' not found
  </code></pre>
  
  <p><strong>My question</strong> is: why does aes correctly map “values” to dt in x=values, but not in y=… ?</p>
  
  <p>NB: The reason I am trying to do this is to put density plots in the diagonal facets in a scatterplot matrix. And yes, I know there are about 5 different ways to generate scatterplot matrices in ggplot.</p>
  
  <p>Thanks in advance to anyone who can help.</p>