为何无法修改gganimate动画的帧数nframes?已解决
解决gganimate结合ffmpeg渲染时的帧率解析错误
问题描述
使用gganimate制作动画,未指定nframes参数时渲染正常,但设置nframes = 300后触发以下错误:
nframes and fps adjusted to match transition Error parsing framerate 8,4. Error: Rendering with ffmpeg failed
重现代码
创建gganim对象的代码:
options(scipen = 999, OutDec = ",") MonthlyAveragePrecipitationMap = ggplot(MonthlyAverageExtremePrecipitation) + geom_path(data = map_data("world","Germany"), aes(x = long, y = lat, group = group)) + coord_fixed(xlim = c(6,15), ylim = c(47,55)) + geom_point(aes(x=lon, y=lat, colour = ShareOfExtremePrecipitationEvents, group = MonthOfYear), size = 3) + scale_color_gradient(low="blue", high="yellow") + xlab("Longitude (degree)") + ylab("Latitude (degree)") + theme_bw() + transition_manual(frames = MonthOfYear) + labs(title = '{unique(MonthlyAverageExtremePrecipitation$MonthOfYear)[as.integer(frame)]}', color = paste0("Share of Extreme Precipitation Events \namong all Precipitation Events"))
调用渲染的代码:
animate(MonthlyAveragePrecipitationMap, nframes = 300, renderer = ffmpeg_renderer( format = "auto", ffmpeg = NULL, options = list(pix_fmt = "yuv420p")))
问题原因
全局设置options(OutDec = ",")将系统默认的小数分隔符从英文点.替换为逗号,,gganimate在计算并传递帧率给ffmpeg时,会使用当前的小数分隔符格式化数值,而ffmpeg仅支持英文点作为小数分隔符,因此无法解析8,4这类格式的帧率值,导致渲染失败。
解决方法
避免全局修改小数分隔符,改为在需要显示逗号分隔小数的局部场景中单独设置:
- 移除全局的
OutDec = ","设置,保留其他必要的全局配置 - 通过坐标轴的
scale_*函数,指定标签的小数格式为逗号分隔
修改后的代码示例:
options(scipen = 999) # 仅保留科学计数法相关设置 MonthlyAveragePrecipitationMap = ggplot(MonthlyAverageExtremePrecipitation) + geom_path(data = map_data("world","Germany"), aes(x = long, y = lat, group = group)) + coord_fixed(xlim = c(6,15), ylim = c(47,55)) + geom_point(aes(x=lon, y=lat, colour = ShareOfExtremePrecipitationEvents, group = MonthOfYear), size = 3) + scale_color_gradient(low="blue", high="yellow") + xlab("Longitude (degree)") + ylab("Latitude (degree)") + # 局部设置坐标轴标签的小数分隔符为逗号 scale_x_continuous(labels = ~format(.x, decimal.mark = ",")) + scale_y_continuous(labels = ~format(.x, decimal.mark = ",")) + theme_bw() + transition_manual(frames = MonthOfYear) + labs(title = '{unique(MonthlyAverageExtremePrecipitation$MonthOfYear)[as.integer(frame)]}', color = paste0("Share of Extreme Precipitation Events \namong all Precipitation Events"))
这样既满足了数据显示时使用逗号作为小数分隔符的需求,又不会干扰gganimate与ffmpeg之间的数值传递,渲染即可正常进行。
内容的提问来源于stack exchange,提问作者RibbitRibbit
相关产品推荐
相关产品推荐

