r - ggsave 和 gganimate 中符号的大小一致 'animate'

标签 r png gif resolution gganimate

我的最终目标是创建两个输出:

1) 显示我所有数据的静态图像,另存为 png
2) 我的数据的动画,保存为 gif

我正在使用 ggplot2gganimate,但我很困惑为什么两种保存方法之间的符号大小不一致。

我尝试调整 dpi 并保存为 jpg 而不是 png,但没有成功。 谁能帮我弄清楚如何使两个输出对象中的宽度、高度和符号大小保持一致?

这是一个显示两个输出的可重现示例。您可以看到 gif 中的黑点较小。

制作png

library(gganimate)
library(ggplot2)

locs <- data.frame(x = c(1, 2, 3, 4, 5, 6),
                   y = c(1, 2, 3, 3.1, 3.2, 6),
                   LDT = c(1, 2, 3, 4, 5, 6))

g <- ggplot(locs, aes(x, y)) +
  geom_point() +
  theme_void() +
  theme(plot.background = element_rect(fill = "pink"))
g
ggsave("test.png", g, width = 2, height = 2, dpi = 100)

enter image description here

制作gif

anim <- g + transition_time(LDT)
animate(anim, duration = 1, fps = 20, width = 200, height = 200)
anim_save("test.gif")

enter image description here

最佳答案

animate() 默认情况下使用 png() 生成帧。

ggsave 调用中,您指定了 100 dpi 的绘图分辨率。

要使用 png 获得相同的结果,您必须设置 res = 100(请参阅 test_png_device.png)。

因此,要使用 animate 获得一致的符号大小,您必须将分辨率传递给 png 作为 animate 的可选参数,如下所示如下:

library(gganimate)
library(ggplot2)
library(gifski)

locs <- data.frame(x = c(1, 2, 3, 4, 5, 6),
                   y = c(1, 2, 3, 3.1, 3.2, 6),
                   LDT = c(1, 2, 3, 4, 5, 6))

g <- ggplot(locs, aes(x, y)) +
  geom_point() +
  theme_void() +
  theme(plot.background = element_rect(fill = "pink"))

ggsave("test.png", g, width = 2, height = 2, dpi = 100)

png(filename = "test_png_device.png", width = 200, height = 200, units = "px", res = 100)
g
dev.off()

anim <- g + transition_time(LDT)
myAnimation <- animate(anim, duration = 1, fps = 20, width = 200, height = 200, renderer = gifski_renderer(), res = 100)
anim_save("test.gif", animation = myAnimation)

ggsave Result


添加:不确定您是否对此感兴趣,但是,我喜欢使用库( plotly )进行动画,因为它默认添加动画 slider 。

这是您的示例的ggplotly方式:

library(plotly)
library(htmlwidgets)

locs <- data.frame(x = c(1, 2, 3, 4, 5, 6),
                   y = c(1, 2, 3, 3.1, 3.2, 6),
                   LDT = c(1, 2, 3, 4, 5, 6))

g <- ggplot(locs, aes(x, y)) + theme_void() + 
  theme(panel.background = element_rect(fill = "pink")) +
  geom_point(aes(frame = LDT))

p <- ggplotly(g) %>% 
  animation_opts(500, easing = "linear", redraw = FALSE)

saveWidget(p, file = "myAnimation.html", selfcontained = TRUE)
browseURL("myAnimation.html")

Here可以找到相关帖子。

关于r - ggsave 和 gganimate 中符号的大小一致 'animate',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58858687/

相关文章:

r - 在 R6 类上实现 S3 调度的正确方法

gif动画完成时javascript触发

python - 从稀疏数据创建 PNG 图像

html - 将 Gif 图像转换为 Base64,同时保留循环计数

ruby-on-rails - 如何在 Paperclip 中制作条件样式?

r - 为什么我在 R 中的 glmer 模型需要这么长时间才能运行?

r - 测量 Shiny 内部的执行速度

r - 如何使用包含两种语言的单独数据框将语言 1 中的单个单词替换为语言 2 中的单词?

ffmpeg - 如何强制 ffmpeg 更频繁地刷新覆盖图像?

image - 如何在 PDF 中插入透明的 PNG?