首页 文章

ggplot右侧的常见图例

提问于
浏览
2

我想将一个共同的图例对齐到情节的右边而不是底部 . 类似的例子在here讨论(史蒂文森的第二个答案)

通过史蒂文森对代码的基本编辑,我将legend.position更改为右,如果我保持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 回答

  • 3

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

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

相关问题