Suppose I have the three following plots (in R):
p1 = hist(rnorm(1000,1,1), 10000)
p2 = hist(rnorm(1000,1,1), 10000)
p3 = hist(rnorm(1000,1,1), 10000)
Is there any way that these can be made into a "gif"?
For example:
library(gifski)
gif_file <- ( "C:/Users/OneDrive/Documents/ref.gif")
save_gif((p1, p2, p3), gif_file, 1280, 720, res = 144)
I am not sure if this statement is intended to be used this way. Does anyone know if this is possible?
(Note: I know that you can do this with a loop (i.e. create p1, p2, p3 with a loop) , but I am specifically interested in knowing if this can be done when p1, p2, p3 have already been created).
Thanks!
CodePudding user response:
Here is a way. Just follow the last example in help("gifski")
.
library(gifski)
makeplot <- function(){
p1 = hist(rnorm(1000,1,1), 10000)
p2 = hist(rnorm(1000,1,1), 10000)
p3 = hist(rnorm(1000,1,1), 10000)
}
set.seed(2021)
gif_file <- "~/tmp/ref.gif"
save_gif(makeplot(), gif_file, 1280, 720, res = 144)
utils::browseURL(gif_file)
Edit
To create a GIF file when the plots already exist must be done in two steps. First create the PNG files from the plots, then create the GIF animation.
set.seed(2021)
p1 <- hist(rnorm(1000,1,1), 10000)
p2 <- hist(rnorm(1000,1,1), 10000)
p3 <- hist(rnorm(1000,1,1), 10000)
plot_list <- list(p1, p2, p3)
png_path <- file.path(tempdir(), "framed.png")
png(png_path)
lapply(plot_list, plot)
#[[1]]
#NULL
#
#[[2]]
#NULL
#
#[[3]]
#NULL
dev.off()
#RStudioGD
# 2
png_files <- sprintf(png_path, seq_along(plot_list))
gif_file2 <- "~/tmp/ref2.gif"
gifski(png_files, gif_file2)
#Inserting image 3 at 2.00s (100%)...
#Encoding to gif... done!
#[1] "/home/rui/tmp/ref2.gif"
utils::browseURL(gif_file2)
Final clean-up
unlink(gif_file)
unlink(gif_file2)
unlink(png_files)