我的最终目标是创建两个输出:
1) 显示我所有数据的静态图像,另存为 png
2) 我的数据的动画,保存为 gif
。
我正在使用 ggplot2
和 gganimate
,但我很困惑为什么两种保存方法之间的符号大小不一致。
我尝试调整 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)
制作gif
anim <- g + transition_time(LDT)
animate(anim, duration = 1, fps = 20, width = 200, height = 200)
anim_save("test.gif")
最佳答案
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)
添加:不确定您是否对此感兴趣,但是,我喜欢使用库( 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/