R中foreach并行绘图报错:plot.new has not been called yet 求解
你的推测完全正确!
你遇到的Error in { : task 1 failed - "plot.new has not been called yet"问题,核心原因就是并行子进程无法访问主进程创建的绘图设备:
- 主进程中调用
plot(Shape, axes=T, asp=1)创建的绘图窗口,是属于主进程的专属资源; foreach %dopar%启动的每个并行任务都是独立的子进程,它们和主进程的内存、运行环境完全隔离,根本看不到主进程打开的绘图设备,所以子进程里调用points()时会报错“还没调用plot.new”。
解决办法
1. 优先选择普通循环(推荐)
绘图属于IO密集型操作,并行不仅不会提速,反而会因为进程通信增加额外开销。直接用普通for循环就能完美解决问题:
library(deldir); library(plyr); library(rgdal); library(doParallel);library(foreach) # 读取矢量数据 Shape <- readOGR(dsn = ".\\Data\\greatlakes_subbasins", layer = "greatlakes_subbasins") idpoly <- lapply(Shape@polygons , slot , "ID") # 主进程创建绘图设备 plot(Shape, axes=T, asp=1) # 循环高亮每个要素的坐标点 for(j in 1:length(idpoly)) { coord <- Shape@polygons[[j]]@Polygons[[1]]@coords coord <- coord[-1,] points(coord, col="orange", pch=20, cex=2) box() }
2. 若必须并行(结合其他计算任务)
如果你的场景中,除了绘图还有大量需要并行的计算逻辑,可以把计算部分并行化,绘图部分统一放到主进程执行:
library(deldir); library(plyr); library(rgdal); library(doParallel);library(foreach) # 初始化并行集群 num_cores <- detectCores() - 1 clust <- makeCluster(num_cores, type = "PSOCK") registerDoParallel(clust) # 读取数据 Shape <- readOGR(dsn = ".\\Data\\greatlakes_subbasins", layer = "greatlakes_subbasins") idpoly <- lapply(Shape@polygons , slot , "ID") # 并行处理坐标(可加入其他计算逻辑) processed_coords <- foreach(j = 1:length(idpoly), .packages = c('rgdal')) %dopar% { coord <- Shape@polygons[[j]]@Polygons[[1]]@coords coord[-1,] # 返回处理后的坐标 } # 关闭并行集群 stopCluster(clust) # 主进程统一绘图 plot(Shape, axes=T, asp=1) for(coord in processed_coords) { points(coord, col="orange", pch=20, cex=2) box() }
内容的提问来源于stack exchange,提问作者RBK
相关产品推荐
相关产品推荐

