Skip to content

Instantly share code, notes, and snippets.

@yihui
Created May 25, 2012 22:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yihui/2790922 to your computer and use it in GitHub Desktop.
Save yihui/2790922 to your computer and use it in GitHub Desktop.
draw a table by gridExtra in knitr
\documentclass{article}
\begin{document}
We can draw a table with the gridExtra package, and one problem is to
pre-determine the size of the table plot to remove the extra white
margin. Below is an example that shows you how to do it (courtesy of
baptiste auguie).
<<setup>>=
library(gridExtra)
g = tableGrob(head(iris, 4))
<<draw-table, dev='png', dpi=150, fig.width=convertWidth(grobWidth(g), "in", value=TRUE), fig.height=convertHeight(grobHeight(g), "in", value=TRUE)>>=
grid.draw(g)
@
\end{document}
@baptiste
Copy link

I'm confused: is <<draw-table>> inside <<setup>>, or is there a missing @? Also, can knitr remove the dummy Rplots.pdf?

@yihui
Copy link
Author

yihui commented May 26, 2012

many people think <<>>= has to be ended by @ but that is not true; the original syntax of literate programming defined <<>>= to open code chunks, and @ to open documentation chunks, so I can use two <<>>= successively and they are two separate chunks; you can certain add @ before the second chunk, but that is unnecessary because there is no text between the two chunks

knitr does not produce Rplots.pdf at all (details at yihui/knitr#9)

@baptiste
Copy link

Thanks, I didn't know that. Regarding Rplots.pdf, it is definitely created when I knit the gist above. Do you mean that it's not knitr's fault that it exists (which is correct, grid opens a device also in interactive use to test the fontsize)?

@yihui
Copy link
Author

yihui commented May 26, 2012

I see. I did not know convertWidth() has to open a device. I'll fix this. Thanks!

@yihui
Copy link
Author

yihui commented May 26, 2012

fixed; will appear in my next commit

@baptiste
Copy link

Thanks!

@1beb
Copy link

1beb commented Sep 7, 2012

Was looking for exactly this! Is there any way to reduce the amount of typing involved? I'm using your code in a similar way with Rmd:

```{r} 
g = tableGrob(head(iris, 4))
```{r draw-table, dev='png', dpi=72, fig.width=convertWidth(grobWidth(g), "in", value=TRUE), fig.height=convertHeight(grobHeight(g), "in", value=TRUE)}
grid.draw(g)
```

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment