Advertisement
Guest User

mygg_animate.r

a guest
Aug 8th, 2017
335
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. mygg_animate <- function (p = last_plot(), filename = NULL, saver = NULL, title_frame = TRUE,
  2. ...)
  3. {
  4. if (is.null(p)) {
  5. stop("no plot to save")
  6. }
  7. built <- ggplot_build(p)
  8. frames <- plyr::compact(lapply(built$data, function(d) d$frame))
  9. titles <- plyr::compact(lapply(built$data, function(d) d$ttl))
  10.  
  11. if (length(frames) == 0) {
  12. stop("No frame aesthetic found; cannot create animation")
  13. }
  14. if (is.factor(frames[[1]])) {
  15. frames <- sort(unique(unlist(frames)))
  16. }
  17. else {
  18. frames.unique <- sort(unique(do.call(c, frames)))
  19. }
  20. frames.unique <- sort(unique(frames.unique))
  21. plots <- lapply(1:length(frames.unique), function(k) {
  22. f <- frames.unique[k]
  23. t <- titles[[1]][which(frames[[1]]==f)[1]]
  24. b <- built
  25. for (i in seq_along(b$data)) {
  26. frame_vec <- b$data[[i]]$frame
  27. if (!is.null(frame_vec)) {
  28. sub <- (frame_vec == f | is.na(frame_vec))
  29. if (!is.null(b$data[[i]]$cumulative)) {
  30. sub <- sub | (b$data[[i]]$cumulative & (frame_vec <=
  31. f))
  32. }
  33. b$data[[i]] <- b$data[[i]][sub, ]
  34. }
  35. }
  36. if (title_frame) {
  37. if (!is.null(b$plot$labels$title)) {
  38. b$plot$labels$title <- paste(b$plot$labels$title,
  39. t)
  40. }
  41. else {
  42. b$plot$labels$title <- t
  43. }
  44. }
  45. b
  46. })
  47. ret <- list(plots = plots, frames = frames.unique)
  48. class(ret) <- "gg_animate"
  49. if (!is.null(filename)) {
  50. gganimate:::gg_animate_save(ret, filename, saver, ...)
  51. ret$saved <- TRUE
  52. }
  53. else {
  54. ret$ani_opts <- list(...)
  55. ret$saved <- FALSE
  56. }
  57. ret
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement