Skip to content

Instantly share code, notes, and snippets.

@thomasp85
Last active December 17, 2021 11:20
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thomasp85/88d6e7883883315314f341d2207122a1 to your computer and use it in GitHub Desktop.
Save thomasp85/88d6e7883883315314f341d2207122a1 to your computer and use it in GitHub Desktop.
An example of animating the build up of a histogram with dropping balls using tweenr, gganimate and ggplot2
library(tweenr) # Available on CRAN
library(ggforce) # Install from thomasp85/ggforce
library(gganimate) # Install from dgrtwo/gganimate
set.seed(2)
x <- sample(9,20, prob=c(1,2,3,4,5,4,3,2,1), replace=T)
df <- data.frame(x = x, y = 15)
dfs <- list(df)
for(i in seq_len(nrow(df))) {
dftemp <- tail(dfs, 1)
dftemp[[1]]$y[i] <- sum(dftemp[[1]]$x[seq_len(i)] == dftemp[[1]]$x[i])
dfs <- append(dfs, dftemp)
}
dfs <- append(dfs, dfs[rep(length(dfs), 3)])
dft <- tween_states(dfs, 10, 1, 'cubic-in', 200)
dft$y <- dft$y - 0.5
dft <- dft[dft$y != 14.5, ]
dft$type <- 'Animate'
dfh <- data.frame(x=x, type = 'Histogram')
p <- ggplot(dft) +
geom_circle(aes(x0=x, y0=y, r=0.5, frame = .frame), n=20, fill = 'steelblue') +
geom_histogram(aes(x=x), data = dfh, fill = 'forestgreen', color = 'black', binwidth = 1) +
coord_fixed(ylim = c(0, 13.5)) +
theme_bw() +
facet_grid(.~type)
animation::ani.options(interval = 1/20)
gg_animate(p, 'hist_ex.gif', title_frame = FALSE)
@thomasp85
Copy link
Author

Result:
hist_ex

@skanskan
Copy link

skanskan commented Jun 7, 2016

Great. I was asking for the left-side picture. Thank you.

@MattCowgill
Copy link

Hi @thomasp85 - any idea how I would do this with the new gganimate API?

@gustavekenedi
Copy link

Hi @thomasp85 - any idea how I would do this with the new gganimate API?

Am trying to do this same animation. I haven't been able to get it to work with the right-hand histogram but this code will get you the left-hand animated graph with the new gganimate syntax:

p <- ggplot(dft) +
  geom_circle(aes(x0=x, y0=y, r=0.5), n=20, fill = 'steelblue') +
  coord_fixed(ylim = c(0, 13.5)) + 
  theme_bw() + 
  transition_manual(.frame)

@maxdrohde
Copy link

I am also interested in knowing how to reproduce this in the new gganimate framework.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment