ggplot2:从列表和常见图例在多页上绘制图形

时间:2018-08-09 15:34:06

标签: r ggplot2 legend

我试图使用帖子ggplot2: Plots over Multiple pages中的代码。我可以使它工作一些,但似乎无法弄清楚如何将每页的图形数更改为4。我的代码每页将显示4个图形,但是在第二页上,它将从列表中的第3个图形开始(它已经在第一页中绘制),重新绘制列表中的第4个,然后转到第5个,第六名,而completley跳过了第七名。

我似乎也无法使pdf输出的左侧文本正常工作。

My data is here

这是我当前拥有的代码:

plist = lapply(split(ChlFPALL, ChlFPALL$Tank), function(d) {
  ggplot(data=d, aes(x=TimePoint, y=Chl, group=Variable, colour=Color, shape=Shape)) +
    geom_line(size=1) +
    geom_point(size=4) + scale_x_continuous(breaks = seq(0, 2, 1)) + 
    geom_point() +
    facet_wrap(~ Tank) +
    scale_y_continuous(limits=c(0, max(ChlFPALL$Chl, na.rm=TRUE))) +

    theme(plot.margin=unit(rep(0.4,4),"lines"),
          axis.title=element_blank()) + theme(plot.subtitle = element_text(vjust = 1), 
                                              plot.caption = element_text(vjust = 1), 
                                               axis.text = element_text(size = 10, 
                                                                                                                 face = "bold", colour = "black"), 
                                              legend.text = element_text(size = 10, 
                                                                         face = "bold"), legend.key = element_rect(fill = NA), 
                                              legend.background = element_rect(fill = NA)) + scale_colour_manual(values = c("Bluegreen" = "#528B8B", "Cryptophyta" = "#8B4513", "Diatoms"="#A52A2A", "Green Algae" = "#008B00", "Total conc." = "#000000", "Yellow substances"= "#EEEE00")) 
})

# Four pages of plots in one PDF file
pdf("FPplotsQs.pdf", 11, 8.5)
for (i in seq(1, length(plist), 2)) {
  grid.arrange(grobs=plist[i:(i+3)], 
               ncol=2, left=expression(bold(paste("Chlorophyll", italic(" a "), mu, gL^-1))), bottom="Time (Hours)")
}
dev.off()

还有,是否有办法在页面上仅显示一个常见的图例?我已经尝试了另一个示例中的代码,但无法使其正常工作。

pdf("FPplotsQs.pdf", 11, 8.5)
for (i in seq(1, length(plist), 2)) {
  ggarrange(grobs=plist[i:(i+3)], 
               ncol=2, left=expression(bold(paste("Chlorophyll", italic(" a "), mu, gL^-1))), bottom="Time (Hours)", common.legend = TRUE)
}
dev.off()

更新: 添加以下代码以保存图形的输出非常完美:

plots <- marrangeGrob(plist, nrow = 2, ncol = 2)

ggsave("multipage.pdf", plots, width = 11, height = 8.5, units = "in")

1 个答案:

答案 0 :(得分:1)

更新: 添加以下代码以保存图形的输出非常完美:

plots <- marrangeGrob(plist, nrow = 2, ncol = 2)

ggsave("multipage.pdf", plots, width = 11, height = 8.5, units = "in")