Using gganimate to export gif
You can do like this:
anim <- animate(p)
magick::image_write(anim, path="myanimation.gif")
How to save frames of gif created using gganimate package
gganimate
has changed a lot since this question was asked. In the current version (0.9.9.9999), there is a way to store each frame as its own file.
First, I need to create the animation, which looks a bit different with the new version of the package:
p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent)) +
geom_point() +
scale_x_log10() +
transition_states(year, 1, 5)
The animation can then be shown using
animate(p)
The rendering is taken care of by so called renderers. To store the animation in a single animated gif, you can use
animate(p, nframes = 24, renderer = gifski_renderer("gganim.gif"))
Note that I have manually set the number of frames to be created. By default, 100 frames are used and I chose a smaller number here. Picking the right number of frames can be a bit tricky at times and if you get weird results, try using more frames.
Alternatively, you can use a file_renderer()
to write each frame to its own file
animate(p, nframes = 24, device = "png",
renderer = file_renderer("~/gganim", prefix = "gganim_plot", overwrite = TRUE))
This will write files named gganim_plot0001.png
, gganim_plot0002.png
, etc. to the directory ~/gganim
. Modify the values for prefix
and device
if you want different file names or different file types. (I set them to the defaults.)
Using gg_animate to create a gif
Update Jul2018: gganimate()
has undergone a rewrite and is now much improved. The previous API is only available through the archived version and should not be expected to work with the new version.
With the new version:
library(gapminder)
library(gganimate)
## standard ggplot2
ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
geom_point(alpha = 0.7, show.legend = FALSE) +
scale_colour_manual(values = country_colors) +
scale_size(range = c(2, 12)) +
scale_x_log10() +
# Here comes the gganimate specific bits
labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') +
transition_time(year) +
ease_aes('linear')
Producing the much smoother graphic
Original Answer:
I found the gganimate package to do quite well at this.
library(gapminder)
library(ggplot2)
theme_set(theme_bw())
p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent, frame = year)) +
geom_point() +
scale_x_log10()
library(gganimate)
gganimate(p)
gganimate(p, "output.gif")
Update Dec2016: gganimate()
now replaces gg_animate()
and adds cowplot
as a dependency (should auto-install once Issue #32 is resolved).
Is there a way to save a gganimate object as a HTML page with animation control buttons?
The following worked for me in RStudio, though I didn't see "current" listed as an option for device in gganimate::animate
:
library(gganimate)
library(animation)
# name the above gganimate example as p
p <- ggplot(mtcars, aes(factor(cyl), mpg)) +
geom_boxplot() +
transition_states(
gear,
transition_length = 2,
state_length = 1
) +
enter_fade() +
exit_shrink() +
ease_aes('sine-in-out')
# pass the animate command to saveHTML
saveHTML(animate(p,
nframes = 10, # fewer frames for simplification
device = "current"),
img.name = "gganimate_plot",
htmlfile = "gg.html")
I got a html file with animation control buttons & an image folder with 10 png files.
Define size for .gif created by gganimate - change dimension / resolution
There can be issues with using the magick
package.
I think a better solution is use the animate()
function in gganimate
to create an object which is then passed to the anim_save()
function. No need to use another package.
library(gganimate)
library(gapminder)
my.animation <-
ggplot(
gapminder,
aes(x = gdpPercap, y = lifeExp, colour = continent, size = pop)
) +
geom_point(alpha = 0.6) +
scale_x_log10() +
transition_time(year)
# animate in a two step process:
animate(my.animation, height = 800, width =800)
anim_save("Gapminder_example.gif")
How to change the resolution of animated plots (gif) in RStudio Viewer?
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)
In this context also check this article, library(ragg)
and setting animate
's parameter device = 'ragg_png'
.
Related Topics
Setting an Individual Color Palette for the Group Variable in Geom_Smooth
How to Averaging Over a Time Period by Hours
Rmarkdown Removes Citation Hyperlink
How to Run a Job Array in R Using the Rscript Command from the Command Line
Is There a Command Similar to Matlab's "Close All" in R? (How to Close All Graphics Devices)
How to Prevent User from Setting the End Date Before the Start Date Using the Shiny Daterangeinput
How to Join Data from 2 Different CSV-Files in R
How to Get Covariance Matrix for Random Effects (Blups/Conditional Modes) from Lme4
Change Background Colour of Knitr::Kable Headers
R - Lattice Xyplot - How to Add Error Bars to Groups and Summary Lines
System Is Computationally Singular: Reciprocal Condition Number in R
Knitr: Object Cannot Be Found When Converting Markdown File into HTML
R: Clustering Results Are Different Everytime I Run
How to Flatten R Data Frame That Contains Lists
R: Pass a List of Filtering Conditions into a Dataframe
Dplyr:How to Find the First-Non Missing String by Groups
Converting Between Matrix Subscripts and Linear Indices (Like Ind2Sub/Sub2Ind in Matlab)