Automatically adjust LaTeX table width to fit pdf using knitr and Rstudio
You can pass a scalebox
argument to print.xtable
like so
<<results='asis'>>=
print(xtable(wide.df), scalebox='0.75')
@
That doesn't automatically resize the table to fit the page (unfortunately xtable
doesn't support a resizebox
argument) but for many applications the above might be good enough.
The problem with your code is that xtable
returns the table wrapped in a table
environment and not just a tabular. What you have to wrap in the resizebox
, however, is the tabular
. The only way I can see to get this to work as you want it is to let xtable return only the tabular
, like so:
\begin{table}
\resizebox{\textwidth}{!} {
<<results='asis'>>=
print(xtable(wide.df), floating=FALSE)
@
}
\end{table}
and then to write the LaTeX code around it manually.
Updating to reflect the changes in code past few years, and the preference for people to typically work in .RMarkdown instead of Rnw file format.
The kableExtra
package in R is the easiest way for adjusting the size of tables. You can scale the width of the table using the function kable_styling(latex_options = "scale_down")
. This will force the table to the width of the page.
kable(iris[1:5,],
format = "latex", booktabs = TRUE) %>%
kable_styling(latex_options = "scale_down")
For more examples of the kableExtra package, check out the package here: https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf
Here is an example MWE:
---
title: "MWE"
author: "Mikey Harper"
date: "7 November 2017"
output: pdf_document
---
```{r setup, include=FALSE}
library(kableExtra)
library(magrittr)
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
# Build the dataframe
wide.df <- cbind(iris[1:10,],iris[1:10,],iris[1:10,])
```
```{r}
# Basic table
knitr::kable(wide.df)
```
```{r}
# Scaled Table
knitr::kable(wide.df, format = "latex", booktabs = TRUE) %>%
kable_styling(latex_options = "scale_down")
```
The following are some typical steps that you can take to shrink the table size.
\setlength{\tabcolsep}{1pt}
\resizebox{\linewidth}{!}{ %% <-- The most effective way to fit a table / figure
\begin{tabular}
...
...
\end{tabular}
} %resizebox
For text use \sf
mode to make the text more visible.