3

I wanted to use gganimate() but couldn't find a workable solution.

I ended up successfully creating something - using the animation package. I was able to create both a GIF and a Video output - but neither was as smooth or as good as I was hoping.

The output is very choppy - if I want to show 20 different breaks using the base "hist" function, the animation only shows around half of them. You can see that the GIF iterates through all the # of bins, but the plots don't update for each step.

Here's the GIF output of my code.

library('ggplot2')
library('animation')

psd_1 <- data.frame(rnorm(5000, 100, 15))

colnames(psd_1)[1] <- "passengers"

ani.options(interval=.25, nmax=20)

a = saveGIF(
  {
    for (i in c(1:20)) {
      hist(psd_1$passengers, breaks=i, main=paste("Histogram with ",i, " bins"),
           xlab="Total Passengers")
    }
  }
  , movie.name="wodies.gif")
oszkar
  • 865
  • 5
  • 21
  • 1
    Note that setting `break=` to a single numeric value doesn't guarantee that number of breaks ("the number is a suggestion only"). Check the `?hist` help page. If you need to have exactly that many bins, you'll need to set the breaks explicitly. For more help you should provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – MrFlick Apr 18 '20 at 18:17
  • The package name is *animation*, not *animate*. – Rui Barradas Apr 18 '20 at 18:35
  • Also, put `ani.options(interval = 0.25, nmax = 50)` outside `saveGIF`, this is set only once. – Rui Barradas Apr 18 '20 at 18:48
  • What is your desired output? – Cyrus Mohammadian Apr 18 '20 at 19:09
  • @RuiBarradas - I updated the text in my question to reference the correct package, and changed my code to move ani.options outside of saveGIF – SevenOvertimes Apr 19 '20 at 01:06
  • @MrFlick - I've updated to show a more complete example of the code. The output creates a GIF, but it doesn't show every iteration of the histogram. – SevenOvertimes Apr 19 '20 at 01:07
  • @CyrusMohammadian - I've got a link to a GIF output above the code, and I want something smoother than that. While you can see it counting through each iteration, the histogram doesn't update for each step. – SevenOvertimes Apr 19 '20 at 01:08

1 Answers1

3

As I mentioned in the comments, if you pass a single number to breaks=, it does not guarantee that number of breaks, it's just a suggestion. If you want to set an exact number, you need to pass in a vector of breaks. You can do

a = saveGIF(
  {
    for (i in c(1:20)) {
      hist(psd_1$passengers, 
           breaks=seq(min(psd_1$passengers), max(psd_1$passengers), length.out=i), 
           main=paste("Histogram with ",i, " bins"), 
           xlab = "Total Passengers")  }
  }
  , movie.name = "wodies.gif")
MrFlick
  • 195,160
  • 17
  • 277
  • 295