2012-08-09 53 views
27

有沒有辦法讓grid.arrange()充當split.screen()?我想安排一張桌子直接放在圖例下方。在ggplot2直方圖中的圖例下插入一個表格

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

生產:

enter image description here

,但我想它大概是這樣的:

enter image description here

我試過split.screen(),但它似乎沒有使用ggplot類型的圖形。有什麼建議麼?謝謝。

+0

檢查此[鏈接](http://learnr.wordpress.com/2009/04/29/ggplot2-labelling-data-series-and-adding-a-data-table /)出來。我不久前需要做同樣的事情,但我不確定這裏的代碼現在是否過時了。 – 2012-08-09 13:32:41

+0

這是一個老問題,如果你想讓它們工作,你必須在下面的答案中更改'opts'。 – durum 2016-11-29 14:29:52

回答

25

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) 

enter image description here

+0

非常明確......並且對輸出有很大的控制 – dickoa 2012-08-09 15:08:53

+0

@Iselzer謝謝你的建議!非常感激 – Elizabeth 2012-08-10 09:44:11

12

首先你應該看看這個Wiki,有很多例子(看看安排好的一個例子)。 因此,使用放入系統的例子,我設法把這個解決方案

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) 

enter image description here

+0

謝謝你,這是非常有益的! – Elizabeth 2012-08-10 09:43:19

+0

維基鏈接已關閉 – ZN13 2016-09-30 11:09:23

+0

@ PajeetRamahari-Mawari-Kulmini非常感謝,它非常有幫助。我更新了鏈接。 – dickoa 2016-09-30 18:05:51