title: Animated heatmap in R
body: <p>I am trying to make an animated heatmap plot using <code>ggplot</code> and (possibly) <code>plot_ly</code>. So far I was able to accomplish two partial goals: </p>
  
  <p>1) I can make animated scatterplot using <code>plot_ly</code>:</p>
  
  <pre><code>dd &lt;- data.frame(f = rep(1:5, c(rep(50, 5))), 
               x = round(runif(250, 10,100),0),
               y = round(runif(250, 10,100),0),
               id = rep(1:50,5)) 
  
  p &lt;- dd %&gt;%
    plot_ly(
      x = ~x,
      y = ~y,
      frame = ~f,
      type = 'scatter',
      mode = 'markers',
      showlegend = F
    )
  p
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/aVDMp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aVDMp.png" alt="Animated scatter plot"></a></p>
  
  <p>However, with the <code>scatter</code> the plot does not convey the information about repeated elements within a frame or between frames. (So far I wasn't able to get the <code>plot_ly</code> with the option <code>heatmap</code> to work.)</p>
  
  <p>2) I can generate heatmaps for each step using <code>ggplot</code> and <code>stat_bin2d</code>.</p>
  
  <pre><code>dd.wide &lt;- reshape(dd, direction="wide", timevar = "f")
  
  for (i in seq(2,length(names(dd.wide)),2)){
    p &lt;- ggplot(dd.wide, aes_(x=as.name(names(dd.wide)[i]),y=as.name(names(dd.wide)[i+1]))) +
      stat_bin2d() +
      xlim(10,100) +
      ylim(10,100) +
      guides(fill = guide_colorbar(barwidth = 1, barheight = 5)) +
      scale_fill_gradientn(colours=rev(heat.colors(10)))
    print(p)
  }
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/b8e00.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b8e00.png" alt="Step 2"></a> <a href="https://i.stack.imgur.com/Ayisn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ayisn.png" alt="Step 5"></a></p>
  
  <p>Bot for the second approach I didn't find a simple way of turning these static plots into nice animation (I can make snapshot-movie but I would like to have smoother transitions between images.)</p>
  
  <p>I also tried to use the <code>ggplotly()</code> but I wasn't able to get it to work.</p>
  
  <p>I would appreciate any advice on how to make the heatmap change like the scatter plot in <code>plot_ly</code> (I am ok using different animation packages).</p>
  
  <p><strong>Update</strong> I wasn't able to get the animated scatter plot to work on the website so I replaced the animation with a snapshot of the plot.</p>