Search code examples
rggplot2rstudiogganimate

How to change the resolution of animated plots (gif) in RStudio Viewer?


I'm currently following this tutorial to learn to create animated plots using the gganimate library.

However I'm already struggling with the first animation. While the animation itself works, its resolution is downscaled as compared to the example on the website. Resizing the 'Viewer' in RStudio does not change the dimensions/resolution. Plotting the image without animation (plot(p)) creates a plot in 'Plots' that has the same dimensions and resolution as the one from the website. Do I need to adjust some settings for the Viewer? I'm working on Windows 10, RStudio Version 1.4.1717, R Version 4.1.1.

The animation from my viewer:

Output in the RStudio Viewer

Appearance of the same animated plot from the website: Example from the gganimate tutorial

Code from the website to create the above animated plot:

library(gganimate)
p <- ggplot(iris, aes(x = Petal.Width, y = Petal.Length)) + 
  geom_point()
anim <- p + 
  transition_states(Species,
                    transition_length = 2,
                    state_length = 1)
anim

Solution

  • I guess those plots shown in the gganimate article were created on a Linux platform. gganimate by default uses the 'png' device for rendering the single frames.

    png() on windows however by default uses the Windows GDI which is not available on Linux (cairographics is used). This is (probably) why the results differ.

    Please see my related answers here and here.

    To get (more or less) the same output on Windows you can do something like this:

    library(gganimate)
    library(gifski)
    
    p <- ggplot(iris, aes(x = Petal.Width, y = Petal.Length)) +
      geom_point()
    anim <- p +
      transition_states(Species,
                        transition_length = 2,
                        state_length = 1)
    myAnimation <- animate(anim, duration = 3.3, fps = 10, width = 1400, height = 865, renderer = gifski_renderer(), res = 200, type = "cairo")
    anim_save("test.gif", animation = myAnimation)
    

    result

    In this context also check this article, library(ragg) and setting animate's parameter device = 'ragg_png'.