for ggplot2的每页多个图

时间:2016-05-24 21:01:13

标签: r ggplot2

我正在尝试使用multiplot在for循环中从ggplot每页编写多个绘图。但是,根据以下示例数据集,PDF仅在单独的页面上显示总共两个图(而不是四个)(而不是每页两个图)。

这就是我目前所拥有的:

> CohData
     Name ScenID ScenName Year VarName Units value
1  Site01      0     Hind 2000     ANC ueq/L 35.34
2  Site01      1       BC 2020     ANC ueq/L 32.86
3  Site01      1       BC 2040     ANC ueq/L 32.25
4  Site02      0     Hind 2000     ANC ueq/L 28.23
5  Site02      1       BC 2020     ANC ueq/L 45.01
6  Site02      1       BC 2040     ANC ueq/L 57.86
7  Site01      0     Hind 2000      pH        5.93
8  Site01      1       BC 2020      pH        5.86
9  Site01      1       BC 2040      pH        5.85
10 Site02      0     Hind 2000      pH        6.40
11 Site02      1       BC 2020      pH        6.63
12 Site02      1       BC 2040      pH        6.75

library(ggplot2)
library(Rmisc)

## Iterate plots and write to PDF
pdf("plots.pdf")
CohData_nohind <- subset(CohData, ScenID > 0)
stream_vars <- list("ANC", "pH")
for (i in unique(CohData_nohind$ScenID)){
  subdata1 <- subset(CohData_nohind, ScenID == i)
  ScenName <- unique(subdata1$ScenName)
  subdata1 <- subset(CohData, ScenID == i | ScenID == 0)
  for (j in stream_vars){
    subdata2 <- subset(subdata1, VarName == j)
    units <- unique(subdata2$Units)
    for (k in unique(subdata2$Name)){
      subdata3 <- subset(subdata2, Name == k)

      if (j=='ANC'){
        plots <- list()
        p <- ggplot(subdata3, aes(x = Year, y = value)) + geom_line() + expand_limits(y=c(0,100)) + 
          ggtitle(paste0(as.character(ScenName),":\n", as.character(k))) + ylab(paste0(j, " (", units, ")"))
        plots[[i]] <- p

      } else if (j=='pH'){
        plots <- list()
        p <- ggplot(subdata3, aes(x = Year, y = value)) + geom_line() + expand_limits(y=c(3,7)) +
          ggtitle(paste0(as.character(ScenName),":\n", as.character(k))) + ylab(paste0(j, " (", units, ")"))
        plots[[i]] <- p

      }
    }
    multiplot(plotlist = plots, cols = 2)
  }
}
dev.off()

完整数据集有五个“名称”,我希望每页有五个图(每个“名称”一个)。有任何建议吗?

0 个答案:

没有答案