在 ggplot2 直方图中的图例下插入表格 [英] Inserting a table under the legend in a ggplot2 histogram

查看:31
本文介绍了在 ggplot2 直方图中的图例下插入表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让grid.arrange()充当split.screen()?我想在图例的正下方安排一张桌子.

Is there anyway to get grid.arrange() to act as split.screen ()? I would like to arrange a table to be located directly underneath the legend.

#create histogram
my_hist<-ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar()

#create inset table
my_table<- tableGrob(head(diamonds)[,1:3],gpar.coretext =gpar(fontsize=8),gpar.coltext=gpar(fontsize=8), gpar.rowtext=gpar(fontsize=8))

grid.arrange(my_hist,my_table, ncol=2)

产生:

但我希望它看起来大致如下:

but I would like it look roughly like this:

我尝试了 split.screen () 但它似乎不适用于 ggplot 类型的图形.有什么建议?谢谢.

I tried split.screen () but it doesn't seem to work with ggplot type graphics. Any suggestions? Thanks.

推荐答案

Dickoa 的回答非常简洁.我的让你可以更好地控制元素.

Dickoa's answer is very neat. Mine gives you more control over the elements.

my_hist <- ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar()

#create inset table
my_table <- tableGrob(head(diamonds)[,1:3], gpar.coretext = gpar(fontsize=8), gpar.coltext=gpar(fontsize=8), gpar.rowtext=gpar(fontsize=8))

#Extract Legend
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]]
  return(legend)}

legend <- g_legend(my_hist)

#Create the viewports, push them, draw and go up
grid.newpage()
vp1 <- viewport(width = 0.75, height = 1, x = 0.375, y = .5)
vpleg <- viewport(width = 0.25, height = 0.5, x = 0.85, y = 0.75)
subvp <- viewport(width = 0.3, height = 0.3, x = 0.85, y = 0.25)
print(my_hist + opts(legend.position = "none"), vp = vp1)
upViewport(0)
pushViewport(vpleg)
grid.draw(legend)
#Make the new viewport active and draw
upViewport(0)
pushViewport(subvp)
grid.draw(my_table)

这篇关于在 ggplot2 直方图中的图例下插入表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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