在几个ggplot2图形之间共享图例时控制绘图布局 [英] Controlling the plot layout when sharing legends between several ggplot2 graphs

查看:1019
本文介绍了在几个ggplot2图形之间共享图例时控制绘图布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个从ggplot2对象中提取图例并在 grid.arrange()中使用它作为自己对象的函数:

Here is a function to extract the legend from a ggplot2 object and use it as a own object in grid.arrange():

https:// github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs

然而,我真的很苦恼:我只想要一行中的情节,但显然情节布局是不可改变的。我相信

However, what i am really struggling with: I want the plots in only one row, but apparently the plot layout is not changeable. I believe that

grid_arrange_shared_legend <- function(...) {
    plots <- list(...)
    g <- ggplotGrob(plots[[1]] + theme(legend.position="bottom"))$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 = 1,
        heights = unit.c(unit(1, "npc") - lheight, lheight))
}

需要嵌套网格.arrange命令,因为 ncol = 1 参数与图例有关。有没有办法做到这一点?

needs a nested grid.arrange command, as the ncol=1 argument is related to the legend. Is there a way to to do this?

推荐答案

您可以提供 nrow = 1 列表为 do.call

do.call(arrangeGrob, c(lapply(plots, function(x)
  x + theme(legend.position="none")), list(nrow = 1)))

我修改了您提供的链接中的示例:

I adapted the example from the link you provided:

library(ggplot2)
library(gridExtra)

grid_arrange_shared_legend <- function(...) {
  plots <- list(...)
  g <- ggplotGrob(plots[[1]] + theme(legend.position="bottom"))$grobs
  legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
  lheight <- sum(legend$height)
  grid.arrange(
    do.call(arrangeGrob, c(lapply(plots, function(x)
      x + theme(legend.position="none")), list(nrow = 1))),
    legend,
    ncol = 1,
    heights = grid::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)

这篇关于在几个ggplot2图形之间共享图例时控制绘图布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆