2016-10-26 4 views
0

ggplot grobとtable grobを整列させるソリューションを見つけるのが難しいです。私は指示hereに従うことを試みたが、私が望む結果をまだ与えなかった。ggplot grobsが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) 

Iは、テーブル内の各セルがヒストグラムに関連するバーに位置合わせされることを希望するが、依然として、T、L、B、Rがレイアウトから実現することを理解できませんでした。デフォルトではThis is the output I got

答えて

0

セルの高さは、テキストに対応するために絶対的な大きさを持っているが、あなたcan change them to relative units彼らはプロットパネルに合わせて拡張するように、guidenceため

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

私はあなたが同じレイアウトを使用していないことを知りました。説明をお寄せいただきありがとうございます – yuskam

関連する問題