不同页面上的多个图表并另存为 pdf

multiple graph on different page and save as pdf

我用facet_wrap函数制作了多个图表,但它们都出现在一页上。我看了很多问题,但不幸的是还没有成功。如果我能以 pdf 格式将其打印为每页一张图,那就太好了。 这是我的数据:

co1<- tibble(age= c(10:14 ), pop=c(10,12,14,16,18), cn= c(10.1,12.1,14.25,16.09,18.3), country ="a")
co2<- tibble(age= c(10:14 ), pop=c(10.5,12.6,14.5,16.5,18.5), cn= c(10.6,12.5,14.3,16.7,18.6), country ="b")
co3<- tibble(age= c(10:14 ), pop=c(10.9,12.9,14.9,16.9,18.9), cn= c(11.9,13.9,15.9,17.9,19.9), country ="c")
df<- rbind(co1,co2,co3)

这是我在一页上制作多个图表的代码:

ggplot(data=df, aes(x=age,group = country))+
  geom_line(aes(y=pop),colour="red")+
  geom_line(aes(y=cn),colour="blue")+
  facet_wrap(~country) +
  scale_y_continuous(labels = scales::comma)+
  xlab("age") + ylab("population")

利用 ggforce::facet_wrap_paginate 你可以:

library(ggforce)
library(tibble)

co1<- tibble(age= c(10:14 ), pop=c(10,12,14,16,18), cn= c(10.1,12.1,14.25,16.09,18.3), country ="a")
co2<- tibble(age= c(10:14 ), pop=c(10.5,12.6,14.5,16.5,18.5), cn= c(10.6,12.5,14.3,16.7,18.6), country ="b")
co3<- tibble(age= c(10:14 ), pop=c(10.9,12.9,14.9,16.9,18.9), cn= c(11.9,13.9,15.9,17.9,19.9), country ="c")
df<- rbind(co1,co2,co3)

pdf("multi_page.pdf", width = 16 / 2.54, height = 12 / 2.54)
lapply(seq_along(unique(df$country)), function(page) {
  ggplot(data=df, aes(x=age,group = country))+
    # If you want a legend: Map on aesthetics! 
    geom_line(aes(y=pop, colour="pop"))+
    geom_line(aes(y=cn,colour="cn"))+
    # Set the colors via scale_xxx_manual 
    scale_color_manual(values = c(pop = "blue", cn = "red")) +
    facet_wrap_paginate(~country, ncol = 1, nrow = 1, page = page) +
    scale_y_continuous(labels = scales::comma)+
    xlab("age") + ylab("population")
})
dev.off()