Jon*_*now 4 plot png r ggplot2 rgl
我rgl为我的数据的每个因子级别生成了包含3D图,并将它们保存为png.我的数据有30个不同的级别,导致30个不同的图像文件.现在我想将这些png组合成一个单独的图.
我会像这样显示它们:

以下示例说明了我想要做的事情:
library(rgl)
library(png)
library(gridExtra)
library(ggplot2)
## creates a png in the working directory which can be used as an example
example(surface3d)
rgl.snapshot("example.png")
rgl.close()
## imports the png files; in the example, the same file is imported multiple times.
if(exists("png.df")) rm(png.df)
for (i in 1:9) {
png.i <- readPNG("example.png")
g <- rasterGrob(png.i, interpolate=TRUE)
g <- g$raster
g <- as.vector(g)
g <- matrix(g, nrow = 256, ncol = 256, dimnames = list(1:256, 1:256))
df.i <- data.frame(i = rep(row.names(g), dim(g)[2]), j = rep(colnames(g), each = dim(g)[1]), col=as.vector(g))
df.i$i <- as.numeric(as.character(df.i$i))
df.i$j <- as.numeric(as.character(df.i$j))
df.i$col <- as.character(df.i$col)
df.i$title <- paste ( "Plot", i)
if(exists("png.df")) {
png.df <- rbind(png.df, df.i)
} else {
png.df <- df.i
}
}
rm(df.i, g)
## plots the data
pl <- ggplot(png.df, aes( x = i, y = j))
pl <- pl + geom_raster(aes(fill = col)) + scale_fill_identity()
pl <- pl + scale_y_reverse()
pl <- pl + facet_wrap( ~ title)
pl <- pl + coord_equal() + theme_bw() + theme(panel.grid = element_blank(), axis.text = element_blank(), axis.title = element_blank(), axis.ticks= element_blank())
pl
Run Code Online (Sandbox Code Playgroud)
这种方法效果很好,但速度很慢.真正的pngs具有更高的分辨率,我想绘制30个png,而不仅仅是9个,这导致我的机器在相当长的时间内完全没有响应(i7,8GB RAM).
输入部分工作得相当好,但结果数据框非常大(4.5e + 07行),ggplot(可以理解)无法正确处理.
如何以快速有效的方式创建情节?优选地使用R,但也可以使用其他软件.
下面是一个使用该解决电网功能grid.raster,并xyplot从格.我认为它grid.raster有更快的渲染到屏幕,所以它是一个很好的性能候选人.我选择晶格是因为它使用面板定制更容易集成网格功能.

首先我readPNG从png包中读取所有png (类似于你的解决方案)
ll <- list.files(path='c:/temp',patt='compo[0-9].*',full.names=T)
library(png)
imgs <- lapply(ll,function(x){
as.raster(readPNG(x)) ## no need to convert to a matrix here!
})
Run Code Online (Sandbox Code Playgroud)
然后我为散点图准备数据:
x = 1:4 ## here 4 because I use 16 plots
y = 1:4
dat <- expand.grid(x,y)
Run Code Online (Sandbox Code Playgroud)
最后我使用xyplot自定义面板功能:
library(lattice)
library(grid)
xyplot(Var2~Var1|rownames(dat),data=dat,layout=c(4,4),
panel=function(x,y,...){
lims <- current.panel.limits()
grid.raster(image =imgs[[panel.number()]],sum(lims$xlim)/2,sum(lims$ylim)/2,
width =diff(lims$xlim),
height=diff(lims$ylim),def='native' )
})
Run Code Online (Sandbox Code Playgroud)
PS:这是我所说的每斤解决方案.