我经历了这个question,但它只绕x轴循环,我怎样才能在x轴和y轴上循环。我尝试如下,但它不打印网格中的每个图: 谢谢!
例如,我有一个数据框:
t <- data.frame(w = c(1, 2, 3, 4), x = c(23,45,23, 34),
y = c(23,34,54, 23), z = c(23,12,54, 32))
在右侧获得常见图例的功能:
grid_arrange_shared_legend <- function(...) {
plots <- list(...)
g <- ggplotGrob(plots[[1]] + theme(legend.position="right"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
lw <- sum(legend$width)
gl <- lapply(plots, function(x) x + theme(legend.position="none"))
grid.arrange(arrangeGrob(grobs = gl), legend,
ncol = 2, widths = unit.c(unit(1, "npc") - lw, lw))
}
实际绘图循环:
qual = c("w", "x")
for(q in qual){
p = lapply(list("y", "z"), function(l) ggplot(t, aes_string(x=l, y=q)) +
geom_point(aes(col=plate_name), size=2.0) +
xlab(l) + ylab(q) +
geom_smooth(method="lm") +
scale_color_brewer(palette = "Paired") +
theme_bw())
#pdf("x_vs_y_gg.pdf", h=3.5*3, w=14)
print(grid_arrange_shared_legend(p[[1]], p[[2]], p[[3]], p[[4]], p[[5]], p[[6]], p[[7]], p[[8]]))
}