Guest User

Untitled

a guest
Dec 16th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. library(data.table)
  2. library(gganimate)
  3. library(ggplot2)
  4.  
  5. #toy example data
  6. dt = data.table(time=1:10, x=round(runif(10, 50, 100), 0))
  7.  
  8. #number of frames per bar
  9. n_frames_per_bar = 20
  10. #create sequence per time (to imitate the bar growing from ground)
  11. split_dt = split(dt, dt$time)
  12. split_dt_fill = lapply(split_dt, function(dti) {
  13. #create sequence of length n per bar for animation
  14. data.table(time=dti$time, x=seq(1, dti$x, length.out = n_frames_per_bar))
  15. })
  16. dt_fill = rbindlist(split_dt_fill)
  17.  
  18. #id each row as its own frame
  19. dt_fill[,frame := 1:.N]
  20.  
  21. #once a bar is grown it needs to stay there
  22. #fill in historical bars at full height in future time periods
  23. split_dt_fill2 = split(dt_fill, dt_fill$time)
  24. split_dt_fill2_backfill = lapply(split_dt_fill2, function(dti){
  25. #get time i
  26. time_i = unique(dti$time)
  27. #make bar for time i a different color
  28. dti[,fill := "time i"]
  29. #backfill bar heights if there is history to fill in
  30. if (time_i > 1) {
  31. #get max bar height for all historical bars
  32. backfill_dt = dt_fill[time < time_i,][order(-frame), .SD[1], by=time][,.(time,x)]
  33. #create a row of max height for each frame in time i
  34. split_backfill_dt = split(backfill_dt, backfill_dt$time)
  35. split_backfill_dt = lapply(split_backfill_dt, function(dtj){
  36. data.table(time=dtj$time, x=dtj$x, frame=dti$frame)
  37. })
  38. backfill_dt = rbindlist(split_backfill_dt)
  39. #label fill group for coloring bars
  40. backfill_dt[,fill := "historical"]
  41.  
  42. out = rbind(dti, backfill_dt)
  43. } else {
  44. out = dti
  45. }
  46.  
  47. out
  48. })
  49. plot_dt = rbindlist(split_dt_fill2_backfill)
  50.  
  51. #plot (using gganimate's frame arg in aes)
  52. p = ggplot(plot_dt, aes(x=time, y=x, frame=frame, fill=fill)) +
  53. geom_bar(stat="identity", position = "identity") +
  54. scale_fill_manual(values=c("steelblue", "steelblue1")) +
  55. guides(fill=FALSE) +
  56. labs(x="Time", y="Value", title="")
  57. #create gif (using interval to specify the time per frame)
  58. gganimate(p, title_frame = FALSE, interval = .001)
Add Comment
Please, Sign In to add comment