【发布时间】:2021-10-17 16:26:52
【问题描述】:
我正在使用 R 编程语言。我正在尝试按照本教程的说明(https://www.nagraj.net/notes/gifs-in-r/)在 R 中制作“gif”动画。
使用内置的“mtcars”数据集,我制作了以下两个图表:
library(ggplot2)
#graph 1
LINES <- data.frame(ind = 1, Startx=c(1,1,1,3,5,6),#horiz lines then vert lines
Starty=c(15,20,35,7,7,7),
Endx=c(3,5,6,3,5,6),
Endy=c(15,20,35,15,20,35))
a = ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point()+
geom_segment(aes(x=Startx,y=Starty,xend=Endx,yend=Endy),data=LINES)+
coord_cartesian(ylim=c(9,36),xlim = c(1.5,6.2))
#graph 2
LINES_1 <- data.frame(ind = 2, Startx=c(2,2,2,4,6,7),#horiz lines then vert lines
Starty=c(16,21,36,8,8,8),
Endx=c(4,6,7,4,6,7),
Endy=c(16,21,36,16,21,36))
b = ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point()+
geom_segment(aes(x=Startx,y=Starty,xend=Endx,yend=Endy),data=LINES_1)+
coord_cartesian(ylim=c(9,36),xlim = c(1.5,6.2))
现在,我正在尝试按照教程中的说明将这两个图表转换为“动画 gif”:
#create joint dataset
Lines_frame = rbind(LINES, LINES_1)
library(magick)
## create a directory to which the images will be written
dir_out <- file.path(tempdir(), "tx-sales")
dir.create(dir_out, recursive = TRUE)
for (y in Lines_frame$ind) {
p <-
Lines_frame %>%
filter(ind == y) %>%
ggplot(aes(mtcars$wt,mtcars$mpg))
theme_minimal() +
labs(x = "wt", y = "mpg")
fp <- file.path(dir_out, paste0(y, ".png"))
ggsave(plot = p,
filename = fp,
device = "png")
}
## list file names and read in
imgs <- list.files(dir_out, full.names = TRUE)
img_list <- lapply(imgs, image_read)
## join the images together
img_joined <- image_join(img_list)
## animate at 2 frames per second
img_animated <- image_animate(img_joined, fps = 2)
## view animated image
img_animated
## save to disk
image_write(image = img_animated,
path = "tx-sales.gif")
但这会返回以下错误:
Saving 3.55 x 4.2 in image
Error: Aesthetics must be either length 1 or the same as the data (6): x and y
Run `rlang::last_error()` to see where the error occurred.
谁能告诉我我做错了什么?有没有更简单的方法来做到这一点?
谢谢
【问题讨论】:
-
您要制作什么动画?对于某些类别的事物,
gganimate包是在 ggplot2 中创建动画的直接方法。 -
@JonSpring:感谢您的回答!我正在尝试使图形“a”动画成图形“b”。这可以使用“gganimate”来完成吗?谢谢!
标签: r ggplot2 animation data-visualization gif