ggplot单独的传说和情节 [英] ggplot separate legend and plot

查看:104
本文介绍了ggplot单独的传说和情节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用网格 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(diamond,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)但已被弃用。


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

  library(gridExtra)
g_legend< -function(a.gplot){
tmp< - ggplot_gtable(ggplot_build(a.gplot))
leg< - 其中(sapply(tmp $ grobs ,函数(x)x $ name)==guide-box)
传说< - tmp $ grobs [[leg]]
传说
}

图例< - g_legend(plot1)

grid.arrange(legend,plot1 + theme(legend.position ='none'),
ncol = 2,nrow = 1,widths = c (1 / 6,5 / 6))

网上有很多例子使用 g_legend 函数。

HTH


I am using the grid lpackage to place my graphs that I made with 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))

The problem is that I want to put the plot on the third row (3,1) - (3,4) and put the legend at the (4,4) position. Unfortunately, I can't really find a way to create just a legend variable. I searched online and the closest that I got was using the older + opts(keep = "legend_box") but that has been deprecated.

older solution.

解决方案

You can get the legend from the grob object of the ggplot. Then you could use the grid.arrange function to position everything.

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

There are lots of examples on the web using the g_legend function.

HTH

这篇关于ggplot单独的传说和情节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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