2012-08-09 2 views
27

grid.arrange()를 split.screen()으로 사용하려면 어떻게해야하나요? 전설 아래에 직접 테이블을 배치하고 싶습니다.ggplot2 막대 그래프의 범례 아래에 표 삽입하기

enter image description here

그러나 나는 다음과 같이 대략 볼 싶습니다 :

#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()를 시도

enter image description here

있지만하지 않는 것 ggplot 유형의 그래픽 작업. 어떤 제안? 감사.

+0

확인이 [링크] (http://learnr.wordpress.com/2009/04/29/ggplot2-labelling-data-series-and-adding-a-data-table /) 밖으로. 얼마전에 똑같은 일을해야했는데, 여기 코드가 시대에 뒤진 것인지 확실하지는 않습니다. –

+0

이것은 이전 질문입니다. 아래의 답변에서 'opts'를 변경해야 작동합니다. – durum

답변

25

을 가질 수 있었다. 내 것은 당신에게 요소에 대한 통제권을 더줍니다.

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

+0

@Iselzer 조언 해 주셔서 감사합니다! 매우 감사 – Elizabeth

12

먼저이 Wiki을 살펴보아야합니다. 많은 예제가 있습니다 (arrangeGrob를보십시오). 그래서 양태에서는 예를 사용하여,이 솔루션 Dickoa의 대답은 매우 깔끔

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

+0

wiki 링크가 죽었습니다 – ZN13

+0

@ PajeetRamahari-Mawari-Kulmini 고마워요, 정말 도움이됩니다. 나는 링크를 업데이트했다. – dickoa

관련 문제