R multiplot 将绘图写入文件网格包

R multiplot write plot to file grid package

我有一个函数可以创建多图(包含许多子图的图)并将其写入文件。

multiplot <- function(plotlist=NULL, cols) {
  require(grid)

  # Make a list from the ... arguments and plotlist
  plots <- c(plotlist)

  numPlots = length(plots)

  # Make the panel
  plotCols = cols                       # Number of columns of plots
  plotRows = ceiling(numPlots/plotCols) # Number of rows needed, calculated from # of cols

  # Set up the page
  grid.newpage()
  pushViewport(viewport(layout = grid.layout(plotRows, plotCols)))
  vplayout <- function(x, y)
    viewport(layout.pos.row = x, layout.pos.col = y)

  # Make each plot, in the correct location
  for (i in 1:numPlots) {
    curRow = ceiling(i/plotCols)
    curCol = (i-1) %% plotCols + 1
    print(plots[[i]], vp = vplayout(curRow, curCol ))
    #title(paste(product_name,'_ROC___AUC = ', mroc$auc))
  }

}

并调用该函数创建以下图:

filepath <- paste(filepath,'/','Norm_Method_',norm_method,'.jpg',sep="")
jpeg(filepath)  
#multiplot(list(ggplot1,ggplot2,ggplot3,ggplot4,ggplot5,ggplot6,ggplot7,ggplot8,linear_pred,roc.plot), cols=4)
multiplot(list(ggplot1,ggplot2,ggplot3,ggplot4,ggplot5,ggplot6,ggplot7,ggplot8,linear_pred), cols=3)
dev.off()

这是错误的情节:

显然图片需要刮擦所以我在 RStudio 中将其最大化并手动保存结果看起来好多了: 知道如何自动将其写入文件 "maximized window" 更好的情节版本吗?

所以我建议使用 gridExtra.

包中的 arrangeGrob 函数

部分示例代码如下:

require(ggplot2)

require(gridExtra)

data(iris)

p<-ggplot(iris)

a<-p+geom_histogram(aes(x=Sepal.Length))+ ggtitle("A plot")
b<-p+geom_histogram(aes(x=Sepal.Width))+ ggtitle("another PLOT")
c<-p+geom_point(aes(x=Sepal.Width, y=Sepal.Length))+ggtitle("PLOT CITY")
a2<-p+geom_histogram(aes(x=Sepal.Length))+ ggtitle("A plot")
b2<-p+geom_histogram(aes(x=Sepal.Width))+ ggtitle("another PLOT")
c2<-p+geom_point(aes(x=Sepal.Width, y=Sepal.Length))+ggtitle("PLOT CITY")

grobula <- arrangeGrob(a,b,c,a2,b2,c2 ,ncol=3, nrow=2,
                             main = textGrob("some plots", gp = gpar(fontsize=18, fontface="bold.italic", fontsize=18)),
                             sub = textGrob("some subtitle", x=0, hjust=-0.5, vjust=0.1, gp = gpar(fontface = "italic", fontsize = 15)))

这会输出一个 object,我称之为 grobula。然后,您可以打印或保存 object,就像普通的 ggplot object(例如 print(grobula)ggsave(grobula,file=x.pdf).

这让你的函数有点多余;您可以将适当的值插入 ncolarrangeGrob 中的 nrow

最后,要在 ggsave 中指定绘图大小,您可以修改 widthheight 参数。您可能还需要调整标题和其他内容的各种文本大小,以使所有内容都适合您的最终组合图。您可以通过更改 element.text 参数来修改 ggplot 标题中的文本大小。您可以在此处找到相应的文档。

http://docs.ggplot2.org/0.9.2.1/theme.html