代码之家  ›  专栏  ›  技术社区  ›  Manasi Shah

ggplot右侧的通用图例

  •  2
  • Manasi Shah  · 技术社区  · 10 年前

    我想将一个常见的图例对齐到绘图的右侧,而不是底部。类似的例子在 here (史蒂文森的第二个回答)

    通过史蒂文森对代码的基本编辑,我改变了传说。如果我保持ncol=1,则图例仍显示在底部,但如果我编辑ncol=2,图例显示在右侧,但图例和绘图之间有很大的空间。

    library(ggplot2)
    library(gridExtra)
    
    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")]]
    lheight <- sum(legend$height)
    grid.arrange(
      do.call(arrangeGrob, lapply(plots, function(x)
      x + theme(legend.position="none"))),
    legend,
    ncol = 2,
    heights = unit.c(unit(1, "npc") - lheight, lheight))
    }
    
    dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
    p1 <- qplot(carat, price, data=dsamp, colour=clarity)
    p2 <- qplot(cut, price, data=dsamp, colour=clarity)
    p3 <- qplot(color, price, data=dsamp, colour=clarity)
    p4 <- qplot(depth, price, data=dsamp, colour=clarity)
    grid_arrange_shared_legend(p1, p2, p3, p4)
    

    如何将图例正确地叠放在情节旁边?我看过一些帖子,但没有一篇帖子真正提到将图例对齐右侧的多个情节。

    感谢您的帮助,谢谢!

    1 回复  |  直到 9 年前
        1
  •  3
  •   baptiste    10 年前

    你想调整宽度,而不是高度

    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))
    }