如何使用网格移动图例位置。安排 [英] How can I move the legend position with grid.arrange

查看:29
本文介绍了如何使用网格移动图例位置。安排的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在一页中排列4个绘图,将图例放置在底部中心

我使用它从其中一个地块获取图例(因为四个地块的图例是相同的)

    get_legend<-function(myggplot){
    tmp <- ggplot_gtable(ggplot_build(myggplot))
    leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
    legend <- tmp$grobs[[leg]]
    return(legend)
    }

然后,我从任何一个地块中获得图例

   legend <- get_legend(p2)

所以对于我使用的图形:

 tt <-grid.arrange(arrangeGrob(p6, p7, p8, p9, legend,
                          nrow = 2, #
                          left = textGrob("Mammalian species richness", rot = 90, vjust = 1, 
                                          gp = gpar(fontsize = 12))))

但我得到的是:

如何将图例移动到中心按钮并具有2行2列? 命令nrowncol不起作用,因为我收到错误消息,也不是

tt  <- tt + theme(legend.position ="bottom"). 

PS。以防万一这些信息很重要,如果我尝试不放置任何图例,我可以根据需要将四个地块放在一个网格中,但是没有图例,所以,您知道这不利于发布。

推荐答案

您可以在grid.arrange中使用参数layout_matrix以获得更多控制。

一个可复制的示例

library(ggplot2)
library(gridExtra)

get_legend<-function(myggplot){
    tmp <- ggplot_gtable(ggplot_build(myggplot))
    leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
    legend <- tmp$grobs[[leg]]
    return(legend)
    }

p <- ggplot()
p2 <- ggplot(mtcars, aes(mpg, wt, col=factor(am))) + geom_point()
legend <- get_legend(p2)


grid.arrange(p, p, p, p, legend, 
             layout_matrix=rbind(c(1,2,3), c(4,5,5)))

这会产生

或者您可能需要

grid.arrange(p, p ,p, p, legend, 
             layout_matrix=rbind(c(1,1,2,2,5), c(3,3,4,4,5)))

这篇关于如何使用网格移动图例位置。安排的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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