我想使用 R markdown 生成一个 pdf 文档,以显示在for循环中使用 ggplot 制作的一系列图。是否可以控制每页上的绘图数量,例如,每页有 2 X 2 的绘图网格?
我想保持灵活性,以便我可以更改图表的总数,以便它分成适当数量的页面。
下面是我使用 ggplot2 和 gridExtra 包的尝试,但我无法控制每页的图形数量,似乎只想将它们挤到单个页面上。我尝试更改 grid.arrange 中的 ncol,nrow,heights,widths 参数,但似乎没有帮助。
---
title: "ggplot Layout"
output: pdf_document
---
```{r,figure2 fig.height=8, fig.width=6,echo=FALSE,message=FALSE}
library(ggplot2)
library(gridExtra)
graphlist<-list()
count <- 1
colnums<-c(1,5,6,7,8,9,10)
for (i in colnums) {
plot.x.name<-names(diamonds[i])
p <- ggplot(data=diamonds,aes_string(x = plot.x.name)) + geom_histogram()
graphlist[[count]]<-p
count <- count+1
}
do.call("grid.arrange",c(graphlist,ncol=2))
```
这段代码(改编自http://kbroman.github.io/knitr_knutshell/pages/figs_tables.html )演示了我正在寻找的东西的类型 ,但不幸的是,这不适用于 ggplot。
---
title: "Example Layout"
output: pdf_document
---
```{r bunch_o_figs,fig.height=8, fig.width=6, message=FALSE,echo=FALSE}
n <- 100
x <- rnorm(n)
par(mfrow=c(2,2), las=1)
for(i in 1:20) {
y <- i*x + rnorm(n)
plot(x, y, main=i)
}
``