在GGPLOT2直方图插入一个表格的传说下(Inserting a table under the

2019-06-17 16:25发布

反正是有得到grid.arrange()作为split.screen()? 我想安排一个表,位于传说中的正下方。

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

生产:

但我想这大概是这样的:

我试图split.screen(),但它似乎并没有与ggplot类型的图形工作。 有什么建议? 谢谢。

Answer 1:

Dickoa的回答很整齐。 雷让您的元素更多的控制。

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)



Answer 2:

首先,你应该看看这个维基 ,有很多例子(看arrangeGrob一个)。 因此,使用放入系统的例子,我设法把这个解决方案

require(gridExtra)
require(ggplot2)

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

## get the legend 
tmp <- ggplot_gtable(ggplot_build(my_hist))
leg <- which(sapply(tmp$grobs, function(x) x$name) ==  "guide-box")
legend <- tmp$grobs[[leg]]

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


### final result 
grid.arrange(my_hist + opts(legend.position = "none"), arrangeGrob(legend, my_table), ncol = 2)



文章来源: Inserting a table under the legend in a ggplot2 histogram
标签: r ggplot2