remi
remi

Reputation: 779

tableGrob alignment and spacing in Rmarkdown/knitr-HTML document

I have the following issues when using the nice feature tableGrob() from gridExtra package to plot a table in an html document produced by Rmarkdown and knitr.

Here is a reproducible example:

library(datasets)
library(dplyr)
mtcars$cyl <- as.factor(mtcars$carb)
carb.mpg <- mtcars %>%
            select(carb,mpg) %>%
            group_by(carb)   %>%
            summarise_each(funs(sum(.,na.rm=TRUE)),-carb) %>%
            arrange(desc(mpg))
##plot the table
tab <- tableGrob(carb.mpg, cols=c("carb","mpg"), 
              theme=ttheme_minimal())
grid.arrange(tab, top=textGrob("Cars MPG per CARB",gp=gpar(fontsize=16,font=1)) )

For knitr general chunk options:

title: "Test with cars"
output: 
html_document:
keep_md: true

{r setoptions, echo=FALSE} library(knitr) opts_chunk$set(message=FALSE,warning=FALSE)

The issue as can been seen from the attached snapshot is the huge spaceenter image description here between the table and its title and legend. It would be also nice if I could left-align the table in the document.

Any help would be much appreciated.

Upvotes: 1

Views: 1664

Answers (2)

remi
remi

Reputation: 779

After some tweaking, I found that the position of the table can be controlled using viewport (x and y); width/height seem obsolete.

#plot the table
 tab <- tableGrob(carb.mpg, cols=c("carb","mpg"), 
          theme=ttheme_minimal())
 grid.newpage()
 vp  <- viewport(width=0.90,height=0.90,x=0.10,y=0.80,clip="on")
 pushViewport(vp)
 grid.draw(tab) 

This solves the problem only partially: the huge vertical space is still there.enter image description here

Perhaps this gives some direction to resolving the issue?

EDIT: one way that worked for me to control the white spaces/margins was to reduce the figure size parameters in knitr chunk options, i.e.,

{r plot mpg cars, fig.height=value, fig.width=value}

Upvotes: 0

baptiste
baptiste

Reputation: 77116

you could try this

tg <- textGrob("Cars MPG per CARB", gp=gpar(fontsize=16,font=1))
grid.arrange(tg, tab, heights=unit.c(grobHeight(tg), sum(tab$heights)),
             vp=viewport(x=unit(0,"npc") + 
                            0.5*unit.pmax(grobWidth(tg), 
                                          sum(tab$widths))))

enter image description here

Upvotes: 0

Related Questions