SevenOvertimes
SevenOvertimes

Reputation: 33

How can I make an animation in R showing a histogram with different bin sizes?

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")

Upvotes: 3

Views: 314

Answers (1)

MrFlick
MrFlick

Reputation: 206207

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")

Upvotes: 3

Related Questions