0

下面我创建了 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)

但我把所有东西都排成一排,底部的常见图例如下:

在此处输入图像描述

4

1 回答 1

1

我想你会喜欢 patchwork 包,它可以将你的地块安排为

((my_hist1 + my_hist2)/
(my_hist3 + my_hist4)/
(my_hist5 + my_hist6)) + 
plot_layout(guides = 'collect')

拼凑的详细布局小插图: https ://patchwork.data-imaginist.com/articles/guides/layout.html

于 2020-05-12T01:18:41.393 回答