Jon Spring
Jon Spring

Reputation: 66870

Animating scales parameter

I'm looking for an elegant/concise way to produce an animation in R that shifts a parameter in a transformation of my y scale.

Let's say I have this data and chart:

library(tidyverse); library(gganimate); library(scales)
my_data <- tibble(time  = 1:100, value = (5*sin(time/100))^6 + (1E3*sin(time/5)))
scale_plot <- function(sig) {
  ggplot(my_data, aes(time, value)) + 
         geom_line() + labs(title = paste("sigma =", {{ sig }})) +
         scale_y_continuous(trans = pseudo_log_trans(sigma = sig))  
}

Depending on whether I want to emphasize global or local effects, I might choose use a different sigma parameter in scales::pseudo_lot_trans():

scale_plot(20000) # pretty close to linear

enter image description here

scale_plot(200)   # toward log

enter image description here

I want an elegant/concise way to produce an animation that shifts between those. I have come across methods that use a loop to generate a series of static images, and then something like gifski or animation to compile them into GIF. (See my answer to another question.) Ideally, I'd like to find a way using gganimate, but so far I've only figured out how to animate changes in the data, or changes in the viewport (e.g. using gganimate::view_manual), not parameters of a transformation. Is there a more concise way to do that than constructing the frames "manually"?

Upvotes: 2

Views: 106

Answers (1)

Jon Spring
Jon Spring

Reputation: 66870

Adopting my answer to another question, this could be approached by creating the frames and then combining them using the animation package. Is there a better approach I'm overlooking using gganimate?

library(animation); library(Cairo)
sig_seq = (10:150)^2
oopt = ani.options(interval = 1/10)
CairoPNG(filename = ani.options("img.fmt"))  #using Cairo device for smoother antialiasing
saveGIF({for (i in 1:length(sig_seq)) {
  print(scale_plot(sig_seq[i]))
  print(paste0(i, " out of ",length(sig_seq)))
  ani.pause()}
},movie.name="sigma_anim.gif", ani.width = 300, ani.height = 200) 

enter image description here

Upvotes: 2

Related Questions