主要的问题是你正在使用
ggplotGrob
在错误的对象上。
grid.arrange
制作多页pdf
第一种方法:使用技巧
GplotGrob
创建空白页
pdf("baseball.pdf", 7, 5)
for (i in seq(1, length(unique(Baseball$team87)), 6)) {
temp <- ggplot(Baseball[Baseball$team87 %in% levels(Baseball$team87)[i:(i+5)], ],
aes(hits86, sal87)) +
geom_point(na.rm=TRUE) +
facet_wrap(~ team87) +
scale_y_continuous(limits=c(0, max(Baseball$sal87, na.rm=TRUE))) +
scale_x_continuous(limits=c(0, max(Baseball$hits86))) +
theme_bw()
pdf(file=NULL)
g <- ggplotGrob(temp)
pos = c(unique(subset(g$layout, grepl("panel", g$layout$name), select = t)))
for(i in pos) g$heights[i-1] = unit(0.4,"cm")
grobs = which(grepl("strip", g$layout$name))
for(i in grobs) g$grobs[[i]]$heights <- unit(1, "npc")
dev.off()
grid.arrange(g)
}
dev.off()
第二种方法:避免使用假冒设备
plotlist <- list()
j <- 1
for (i in seq(1, length(unique(Baseball$team87)), 6)) {
temp <- ggplot(Baseball[Baseball$team87 %in% levels(Baseball$team87)[i:(i+5)], ],
aes(hits86, sal87)) +
geom_point(na.rm=TRUE) +
facet_wrap(~ team87) +
scale_y_continuous(limits=c(0, max(Baseball$sal87, na.rm=TRUE))) +
scale_x_continuous(limits=c(0, max(Baseball$hits86))) +
theme_bw()
g <- ggplotGrob(temp)
pos = c(unique(subset(g$layout, grepl("panel", g$layout$name), select = t)))
for(i in pos) g$heights[i-1] = unit(0.4,"cm")
grobs = which(grepl("strip", g$layout$name))
for(i in grobs) g$grobs[[i]]$heights <- unit(1, "npc")
plotlist[[j]] <- g
j <- j+1
}
pdf("baseball.pdf", 7, 5)
for (i in (1:length(plotlist))) {
grid.arrange(plotlist[[i]])
}
dev.off()
实际上,你甚至可以使用
网格排列
和
GplotGrob
facet
使其更加可定制。