欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

如何使用R语言亲手制作GIF和PNG动画教程

最编程 2024-02-18 07:19:27
...

Gifski包将图像帧转换为高质量的GIF动画。要么提供输入png文件,要么从R图形设备自动渲染动画图形。


主函数gifski()

gifski(png_files,
 gif_file = "animation.gif",
  width = 800,
   height = 600,
  delay = 0.5,
   loop = TRUE, 
   progress = TRUE
 )
png_files vector of png files png文件的向量
gif_file output gif file 输出gif文件
width gif width in pixels gif宽度(像素)
height gif height in pixel 以像素为单位的gif高度
delay time to show each image in seconds 以秒为单位显示每个图像的时间
loop should the gif play forever (FALSE to only play once) gif应该永远播放吗(FALSE只播放一次)
progress show progress bar 显示进度条
expr an R expression that creates graphics 创建图形的R表达式
... other graphical parameters passed topng 支持一些传递给png的其他图形参数
# Thu Aug 27 09:08:50 2020 -
# 字符编码:UTF-8
# R 版本:R x64 4.0.2
# cgh163email@163.com
# —— 拎了个梨????
# 
# Gifski将图像帧转换为高质量的GIF动画。要么提供输入png文件,要么从R图形设备自动渲染动画图形。
require(gifski)
library(gapminder)
library(ggplot2)
require(utils)
# Thu Aug 27 09:15:17 2020 --#手动将png文件转换为gif----------------------------
png_path <- file.path(tempdir(), "frame%03d.png")
png(png_path)
par(ask = FALSE)
for(i in 1:10)
  plot(rnorm(i * 10), main = i)
dev.off()
png_files <- sprintf(png_path, 1:10)
gif_file <- tempfile(fileext = ".gif")
gifski(png_files, gif_file)
unlink(png_files)
utils::browseURL(gif_file) #  调用系统默认软件打开
# Thu Aug 27 09:25:13 2020 -DIY-------
setwd("O:\\Users\\cp020\\Videos\\Captures") #  设置png文件路径
fp <- list.files(pattern = "*.png$", full.names = TRUE);head(fp)#获取所有同类型文件
gifski(fp,'aac.gif') # 保存
browseURL('aac.gif') #  系统默认打开
# unlink(fp) # 删除文件和目录
# Thu Aug 27 09:18:08 2020 --从gganimate借用的示例----------------------------
# library(gapminder)
# library(ggplot2)
makeplot <- function(){
  datalist <- split(gapminder, gapminder$year)
  lapply(datalist, function(data){
    p <- ggplot(data, aes(gdpPercap, lifeExp, size = pop, color = continent)) +
      scale_size("population", limits = range(gapminder$pop)) + geom_point() + ylim(20, 90) +
      scale_x_log10(limits = range(gapminder$gdpPercap)) + ggtitle(data$year) + theme_classic()
    print(p)
  })
}
# 指定分辨率:
# gif_file <- file.path(tempdir(), 'gapminder.gif')
gif_file <- 'exw.gif'  #  保存GIF文件的地址和文件名
save_gif(makeplot(), gif_file, 1280, 720, res = 144)
utils::browseURL(gif_file) # 调用系统软件打开
实例