title: Specifying the scale for the density in ggplot2's stat_density2d
body: <p>I'm looking to create multiple density graphs, to make an "animated heat map."</p>
  
  <p>Since each frame of the animation should be comparable, I'd like the density -> color mapping on each graph to be the same for all of them, even if the range of the data changes for each one.</p>
  
  <p>Here's the code I'd use for each individual graph:</p>
  
  <pre><code>ggplot(data= this_df, aes(x=X, y=Y) ) + 
      geom_point(aes(color= as.factor(condition)), alpha= .25) +
      coord_cartesian(ylim= c(0, 768), xlim= c(0,1024)) + scale_y_reverse() +
      stat_density2d(mapping= aes(alpha = ..level..), geom="polygon", bins=3, size=1)
  </code></pre>
  
  <p>Imagine I use this same code, but 'this_df' changes on each frame. So in one graph, maybe density ranges from 0 to 4e-4. On another, density ranges from 0 to 4e-2. </p>
  
  <p>By default, ggplot will calculate a distinct density -> color mapping for each of these. But this would mean the two graphs-- the two frames of the animation--aren't really comparable. If this were a histogram or density plot, I'd simply make a call to coord_cartesian and change the x and y lim. But for the density plot, I have no idea how to change the scale.</p>
  
  <p>The closest I could find is this:</p>
  
  <p><a href="https://stackoverflow.com/questions/24078774/overlay-two-ggplot2-stat-density2d-plots-with-alpha-channels">Overlay two ggplot2 stat_density2d plots with alpha channels</a></p>
  
  <p>But I don't have the option of putting the two density plots on the same graph, since I want them to be distinct frames.</p>
  
  <p>Any help would be hugely appreciated!</p>
  
  <p>EDIT:</p>
  
  <p>Here's a reproducible example:</p>
  
  <pre><code>set.seed(4)
  g = list(NA,NA)
  for (i in 1:2) {
  
    sdev = runif(1)
    X = rnorm(1000, mean = 512, sd= 300*sdev)
    Y = rnorm(1000, mean = 384, sd= 200*sdev)
  
    this_df = as.data.frame( cbind(X = X,Y = Y, condition = 1:2) )
  
    g[[i]] = ggplot(data= this_df, aes(x=X, y=Y) ) + 
      geom_point(aes(color= as.factor(condition)), alpha= .25) +
      coord_cartesian(ylim= c(0, 768), xlim= c(0,1024)) + scale_y_reverse() +
      stat_density2d(mapping= aes(alpha = ..level.., color= as.factor(condition)), geom="contour", bins=4, size= 2) 
  
  }
  print(g) # level has a different scale for each
  </code></pre>