r - 生成 ggplot 网格的多页 pdf 文件

标签 r

我正在尝试从 ggplots 列表中生成 ggplots 网格的多页 pdf。我尝试了很多方法来做到这一点,但都没有成功。这是与我一直在使用的可重复的等效内容:

library(ggplot2)

# generate a data frame w same structure as the one I'm working with
time <- c(1:10)
veclist <- list()
veclist[[1]] <- time

for (i in 2:25){
  veclist[[i]] <- as.vector(c(runif(10,-2,2)))
}

d <- as.data.frame(do.call(rbind, veclist))
d <- as.data.frame(t(d))

colnames(d)[1] <- "time"
for (i in 2:length(d)){
  colnames(d)[i] <- paste("name",i,sep=" ")
}

# for a common axis
numericvalues <- d[,2:length(d)]

# generate plot(s)

name_list = paste("`",names(d),"`",sep="")

plot_list = list()
for (i in 2:length(d)) {
  p = ggplot(d, aes_string(x=name_list[[1]], y=name_list[[i]])) +
    geom_point() +
    labs(x="time",title=paste(strwrap(names(d[i]), width = 30),collapse = "\n")) +
    theme(plot.title = element_text(size=10,hjust = 0.5),axis.text.x=element_text(size=6)) +
    coord_cartesian(ylim = c(min(numericvalues, na.rm = TRUE), max(numericvalues, na.rm = TRUE)))
  plot_list[[i]] = p
}

我正在寻找的内容会在plot_list中生成多页pdf网格图(理想情况下每页有3列,4行图)。

我尝试过的一些事情:

pdf("test.pdf")
do.call("marrangeGrob",c(plot_list,ncol=3,nrow=2))

生成无法读取的 pdf 文件。

pdf("test.pdf")
do.call("grid.arrange",c(plot_list))

仅返回“gList”错误中允许的“grobs”。

最佳答案

这会产生多页布局:

library(gridExtra)
...
plot_list = list()
for (i in 2:length(d)) {
  p = ggplot(...)
  plot_list[[i]] = ggplotGrob(p)
}
class(plot_list) <- c("arrangelist", class(plot_list))
ggsave("multipage.pdf", plot_list)

关于r - 生成 ggplot 网格的多页 pdf 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47007642/

相关文章:

r - 如何使用group_by()和summary()来统计数据点的出现次数?

重新安装 R linux ubuntu : unmet dependencies R

c++ - 'unlockEnvironment' 通过 'Rcpp' 而不是 'inline' 实现

r - 避免 "pandoc document conversion failed with error 61"为 `github_document`

r - 将数值向量拆分为不相等的部分,然后将自定义函数应用于每个部分

r - 如何确定哪个R包包含一个函数?

r - 美学必须是长度为 1 或与数据问题相同的长度

java - rJava 安装错误 "JAVA_HOME cannot be determined from the Registry"

r - 如何让 webshot 与 bookdown 一起使用?

r - R中data.table的编程子集