 # how to make an animated histogram from a binomial distribution

Hi! I am currently struggling to make this code of mine into an ongoing loop. Here is my code:

for (pi in seq(0,1,0.1)) {
x <- seq(0,10,by=1)
y <- dbinom(1, x,pi)
barplot(y,xlim=c(0,10),ylim=c(0,1), col = blue)
Sys.sleep(1)
print(y)
}

I need to create a GIF (or animation) of a binomial distribution that loops on forever. The animation must display a histogram with the bars going up and down as n changes.

I would look into using gganimate
https://gganimate.com/articles/gganimate.html

While I could do the work and provide you a solution on a plate. You won't have learned anything. I think you should work through the gganimate guide. Trying every example and understanding why it works. In fact you should probably start with a basics guide of ggplot2 first. I.e do not use barplot. Use an appropriate ggplot geom

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

I did try to use gganimate, but it does not seem to work. This is my code:

install.packages("gganimate")
install.packages("ggplot2")
library(gganimate)
library(ggplot2)
a <- for (pi in seq(0,1,0.1)) {
x <- seq(0,10,by=1)
y <- dbinom(1, x,pi)
barplot(y,xlim=c(0,10),ylim=c(0,1), col = "blue")
Sys.sleep(1)
print(y)
}
anim <- a + transition_states(y,transition_length = 2, state_length = 1)
anim
NULL

I figured out that I need to use the animation package and not gganimate because my code consists of 2 vectors. My new code is:

install.packages("animation")
library(animation)
saveGIF({for (pi in seq(0,1,0.1)) {
x <- seq(1,11,by=1)
y <- dbinom(1, x,pi)
barplot(y,xlim=c(0,10),ylim=c(0,1), col = "blue", main = "n=10", names.arg=c(0,1,2,3,4,5,6,7,8,9,10))
Sys.sleep(1)
print(y)
ani.record()}
})

I cannot get all the frames to come together in a loop even when I said "ani.record" it gives me an error. Do you maybe know how i can create the gif with all my frames already created?

You have installed ImageMagick as the animate docs say you should?