我使用facet_wrap
函数制作了多个图,但它们都显示在一个页面上。我想了很多问题,但遗憾的是还没有成功。如果我能把它打印成pdf格式的每页1张图,那就太好了。这是我的数据:
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()