【问题标题】:ggplot separate legend and plotggplot 单独的图例和绘图
【发布时间】:2012-09-14 09:31:23
【问题描述】:

我正在使用 grid lpackage 来放置我用 ggplot2 制作的图表:

library(ggplot2)
library(grid)

Layout <- grid.layout(nrow = 4, ncol = 4,
          widths = unit(1, "null"), 
          heights = unit(c(0.4, 0.8, 1.2, 1.2), c("null", "null", "null")))
grid.show.layout(Layout)

plot1 = ggplot(diamonds, aes(clarity, fill = color)) + 
            geom_bar() + 
            facet_wrap(~cut, nrow = 1)
print(plot1 + theme(legend.position = "none"), 
vp = viewport(layout.pos.row = 3, layout.pos.col = 1:4))

问题是我想把图放在第三行 (3,1) - (3,4) 并将图例放在 (4,4) 位置。不幸的是,我真的找不到创建图例变量的方法。 我在网上搜索,我得到的最接近的是使用旧的 + opts(keep = "legend_box") 但已被弃用。

older solution.

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    您可以从 ggplot 的 grob 对象中获取图例。然后您可以使用grid.arrange 函数来定位所有内容。

    library(gridExtra)
    g_legend<-function(a.gplot){
        tmp <- ggplot_gtable(ggplot_build(a.gplot))
        leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
        legend <- tmp$grobs[[leg]]
        legend
    }
    
    legend <- g_legend(plot1)
    
    grid.arrange(legend, plot1+ theme(legend.position = 'none'), 
        ncol=2, nrow=1, widths=c(1/6,5/6))
    

    网络上有很多使用g_legend 函数的示例。

    HTH

    【讨论】:

    • 谢谢。我还没有适应新的变化。
    【解决方案2】:

    有一个ggplot2开发者自己推荐的grid_arrange_shared_legend函数:https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs,效果不错。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-20
      • 2018-11-24
      • 1970-01-01
      相关资源
      最近更新 更多