下面我创建了 6 个 ggplots,我的目标是显示它们,如下所示 - 第一列用于 3 个图,第二列用于其余 3 个图,一列用于第一行中的共享图例。图例下方是我的第二个情节小:
我尝试使用此处找到的 Legends 方法:
library(ggplot2)
library(grid)
library(gridExtra)
my_hist1 <- ggplot(diamonds, aes(clarity, fill = cut)) +
geom_bar() +theme(legend.position = "none")
my_hist2 <- ggplot(diamonds, aes(clarity, fill = cut)) +
geom_bar() +theme(legend.position = "none")
my_hist3 <- ggplot(diamonds, aes(clarity, fill = cut)) +
geom_bar()
my_hist4 <- ggplot(diamonds, aes(clarity, fill = cut)) +
geom_bar() +theme(legend.position = "none")
my_hist5 <- ggplot(diamonds, aes(clarity, fill = cut)) +
geom_bar() +theme(legend.position = "none")
my_hist6 <- ggplot(diamonds, aes(clarity, fill = cut)) +
geom_bar()
grid_arrange_shared_legend <-
function(...,
ncol = length(list(...)),
nrow = 1,
position = c("bottom", "right")) {
plots <- list(...)
position <- match.arg(position)
g <-
ggplotGrob(plots[[1]] + theme(legend.position = position))$grobs
legend <- g[[which(sapply(g, function(x)
x$name) == "guide-box")]]
lheight <- sum(legend$height)
lwidth <- sum(legend$width)
gl <- lapply(plots, function(x)
x + theme(legend.position = "none"))
gl <- c(gl, ncol = ncol, nrow = nrow)
combined <- switch(
position,
"bottom" = arrangeGrob(
do.call(arrangeGrob, gl),
legend,
ncol = 1,
heights = unit.c(unit(1, "npc") - lheight, lheight)
),
"right" = arrangeGrob(
do.call(arrangeGrob, gl),
legend,
ncol = 2,
widths = unit.c(unit(1, "npc") - lwidth, lwidth)
)
)
grid.newpage()
grid.draw(combined)
# return gtable invisibly
invisible(combined)
}
grid_arrange_shared_legend(my_hist1,my_hist2,my_hist3,my_hist4,my_hist5,my_hist6)
但我把所有东西都排成一排,底部的常见图例如下:

