0

我使用包含一万个条目的大型数据集ggplot2构建了一个动画图。magick

基于我的帖子如何使用动画 ggplot2-plot 管理并行处理?,我现在不再关心加快绘图过程,而是通过使用并行处理来保存绘图的过程snowfall,因为这是代码中最耗时的部分。问题是,保存绘图需要遍历列表中的所有绘图,这使得代码非常慢。

这是演示我的问题的示例代码:

library(parallel)
library(snowfall)
library(ggplot2)
library(magick)

# creating some sample data for one year
# 4 categories; each category has a specific value per day
set.seed(1)
x <- data.frame(
  rep(as.Date((Sys.Date()-364):Sys.Date(), origin="1970-01-01"),4),
  c(rep("cat01",length.out=365),
    rep("cat02",length.out=365),
    rep("cat03",length.out=365),
    rep("cat04",length.out=365)),
  sample(0:50,365*4, replace=TRUE)
)
colnames(x) <- c("date", "category", "value")
x$category <- factor(x$category)

# creating a cumulative measure making the graphs appear "growing"
x$cumsum <- NA
for(i in levels(x$category)){
  x$cumsum[x$category == i] <- cumsum(x$value[x$category == i])
}
x <- x[order(x$date),]

# number of cores
cores <- detectCores()

# clustering
sfInit(parallel = TRUE, cpus = cores, type = "SOCK")

# splitting data for plotting
datalist <- split(x, x$date)

# making everything accessible in the cluster
sfExportAll()
sfLibrary(ggplot2)
sfLibrary(magick)

# plotting
out <- sfLapply(datalist, function(data){
  plot <- ggplot(data)+
    geom_bar(aes(category, cumsum), stat = "identity")+
    # holding breaks and limits constant per plot
    scale_y_continuous(expand = c(0,0), 
                       breaks = seq(0,max(x$cumsum)+500,500), 
                       limits = c(0,max(x$cumsum)+500))+
    ggtitle(data$date)
plot
})
# accessing changed data
sfExportAll()

# opening magick-device
img <- image_graph(1000, 700, res = 96)

sfLapply(names(out), function(x){out[[x]]}) 

dev.off()

# animation
animation <- image_animate(img, fps = 5)
animation

# closing cluster
sfRemoveAll()
sfStop()

有什么建议可以加快保存过程吗?

我担心这些线路的速度:

img <- image_graph(1000, 700, res = 96) 
sfLapply(names(out), function(x){print(out[[x]])}) 
dev.off()

谢谢!

4

0 回答 0