ggplot grobs align with tableGrob

前端 未结 2 974
傲寒
傲寒 2020-12-19 17:57

I\'m having difficulty to find solution for aligning ggplot grob and table grob. I tried to follow the instruction here but still didn\'t give the results I wanted.

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-19 18:15

    By default the cell heights have absolute sizes to accommodate the text, but you can change them to relative units so that they scale with the plot panel,

    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)
    

提交回复
热议问题