2016-10-26 24 views
0

我很難找到對齊ggplot grob和table grob的解決方案。我試圖按照指示here,但仍然沒有給我想要的結果。ggplot grobs align with tableGrob

library(grid) 
library(gridExtra) 
library(ggplot2) 
library(tibble) 
library(gtable) 
dat <- tibble::rownames_to_column(mtcars, "car") #convert rownames to first col 

plot1 <- ggplot(dat, aes(car, mpg)) + 
    geom_bar(stat = "identity") + 
    coord_flip() 

g1 <- ggplotGrob(plot1) 
tb1 <- tableGrob(dat$cyl) 
g1 <- gtable_add_cols(g1, unit(0.2, "npc")) 
g1 <- gtable_add_grob(g1, grobs = tb1, t=3, l=ncol(g1), b=6, r=ncol(g1)) 

grid.newpage() 
grid.draw(g1) 

我想的是,在表中的每個單元格中的直方圖對齊相關的吧,但還是沒能明白是怎麼T,L,B,R可以從佈局來實現。 This is the output I got

回答

0

默認情況下,細胞的高度有絕對的大小以容納文本,但你can change them to relative units,讓他們擴大與劇情面板,

library(grid) 
library(gridExtra) 
library(ggplot2) 
library(tibble) 
library(gtable) 
dat <- tibble::rownames_to_column(mtcars, "car") #convert rownames to first col 

plot1 <- ggplot(dat, aes(car, mpg)) + 
    geom_bar(stat = "identity") + 
    coord_flip() 

g1 <- ggplotGrob(plot1) 
tb1 <- tableGrob(dat$cyl, theme = ttheme_default(10)) 
tb1$heights = unit(rep(1/(nrow(tb1)), nrow(tb1)), "npc") 
tb1$widths = unit.pmax(tb1$widths, unit(2, "lines")) 
g1 <- gtable_add_cols(g1, sum(tb1$widths)) 
g1 <- gtable_add_grob(g1, grobs = tb1, t=6, l=ncol(g1), b=6, r=ncol(g1)) 

grid.newpage() 
grid.draw(g1) 

enter image description here

+0

感謝您的指導做好,但我還是不要不明白爲什麼t = 6和b = 6。當我用'gtable_show_layout(g1)'查看佈局時,單元格是(3,6) – yuskam

+0

@yuskam真的嗎? https://i.stack.imgur.com/sxXCm.png – baptiste

+0

我現在看到你沒有使用我使用的plot1圖,它給出了不同的佈局。再次感謝您的解釋 – yuskam