R:将多个图表从文件列表保存到单个文件(png或pdf或其他格式) [英] R: Save multiple plots from a file list into a single file (png or pdf or other format)

查看:248
本文介绍了R:将多个图表从文件列表保存到单个文件(png或pdf或其他格式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有10多个文件(最后有数百个文件...).我以png格式用R生成的文件保存到了文件夹中.

I have more than 10 files (in the end some hundreds...). which I generated in R in png format saved into a folder.

我的问题:如何将这些文件保存到多图中(例如,一页上的4位数字以2行2列的形式排列)?

My question: How could I save these files into a multiplot (e.g. 4 figures on one page arranged in 2 rows and 2 columns)?

我知道这可以通过使用par(mfrow=c(2,2))并入绘图循环中,但是如何在生成文件后仅调用文件夹中的文件呢?

I know that this is possible to incorporate inside a plot loop by using par(mfrow=c(2,2)) but how could I do this outside just calling the files in the folder after they are generated?

推荐答案

这里是一种聚合许多png文件的快速方法:

Here a fast method to aggregate many png files:

  1. 使用readPNG
  2. 阅读您的png
  3. 将它们转换为栅格,并使用grid.raster进行绘制:非常有效.
  1. read your png using readPNG
  2. convert them to a raster , and plot them using grid.raster: very efficient.

类似这样的东西:

library(png)
library(grid)
pdf('somefile1.pdf')
lapply(ll <- list.files(patt='.*[.]png'),function(x){
  img <- as.raster(readPNG(x))
  grid.newpage()
  grid.raster(img, interpolate = FALSE)

})
dev.off()

加载png,将其排列并合并到同一pdf中:

首先,您应该使用rasterGrob将png文件存储在grob列表中:

Edit : loading png , arranging them and merge them in the same pdf :

First you should store your png files in a list of grobs using rasterGrob :

plots <- lapply(ll <- list.files(patt='.*[.]png'),function(x){
  img <- as.raster(readPNG(x))
  rasterGrob(img, interpolate = FALSE)
})

然后使用出色的便捷功能marrangeGrob保存它们:

Then save them using the excellent handy function marrangeGrob :

library(ggplot2)
library(gridExtra)
ggsave("multipage.pdf", marrangeGrob(grobs=plots, nrow=2, ncol=2))

这篇关于R:将多个图表从文件列表保存到单个文件(png或pdf或其他格式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆