stats_noob
stats_noob

Reputation: 5907

Animate Histograms in R

I am trying to animate histograms in R. I created the following dataset:

   library(ggplot2)
library(gganimate)

a = abs(rnorm(100,10,10))
b = abs(rnorm(100,10,10))
i = 1
c = data.frame(a,b,i)

a = abs(rnorm(100,10,10))
b = abs(rnorm(100,10,10))
i = 2
d = data.frame(a,b,i)

a = abs(rnorm(100,10,10))
b = abs(rnorm(100,10,10))
i = 3
e = data.frame(a,b,i)

#data
g = rbind(c,d,e)

I was able to make static histograms in base R as well as in ggplot:

myplot1 = plot(g$a, type = "h")


myplot2 = ggplot(g, aes(x=a)) + 
  geom_histogram(binwidth=1)

enter image description here

The problem is when I try to animate these graphs (these are 3 graphs : i = 1,2,3):

#first attempt
animateplot <- myplot1 + transition_time(i)

animateplot

NULL

#second attempt

anim <- myplot2 + transition_manual(g$i) +
  ease_aes("linear") +
  enter_fade() +
  exit_fade()

anim

NULL

Can someone please show me how to animate these graphs and save the animations as a gif or html file?

Thanks!

Upvotes: 0

Views: 767

Answers (1)

Jon Spring
Jon Spring

Reputation: 66480

ggplot(g, aes(x=a)) + 
  geom_histogram(binwidth=1) +
  transition_states(i)

enter image description here

Or a variation using more options:

# alternative fake data
g <- data.frame(a = c(rnorm(500,10,5), rnorm(2000, 20, 30), rnorm(180, 50, 2)),
                i = c(rep(1, 500), rep(2, 2000), rep(3, 180)))

animate(
  ggplot(g, aes(x=a)) + 
  geom_histogram(binwidth=1) +
  transition_states(i, state_length = 0.2) +
  labs(title = "Group: {closest_state}"),
  fps = 25)

enter image description here

Upvotes: 2

Related Questions