Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align xtable caption left in knitr

I have read a bunch of different posts on justifying xtable tables left but I cannot find details/work out how to make the caption justify left as well. Below is a reproducible example which justifies the table left but leaves the caption centred.

\documentclass{article}
\begin{document}

<<echo = F, results = "asis">>=
df = data.frame(x = c(1,2), y = c(4,6))
library(xtable)
print(xtable(df,digits=0, caption="Caption Left?"), include.colnames=TRUE, size = "small", comment=FALSE,   latex.environments="flushleft")
@
\end{document}

Output table

like image 939
Robin Avatar asked Mar 08 '23 02:03

Robin


2 Answers

I have found out how to do this. Simply import the LaTex Caption package and use the caption setup argument:

\captionsetup{justification = raggedright, singlelinecheck = false}

This will justify the caption to the left. The caption can be returned to its default centred position for additional tables or figures by repeating the function with the following modification before additional tables/figures.

\captionsetup{justification = centering, singlelinecheck = false}

The answered solution is:

\documentclass{article}
\usepackage{caption}
\begin{document}
\captionsetup{justification = raggedright, singlelinecheck = false}
<<echo = F, results = "asis">>=
df = data.frame(x = c(1,2), y = c(4,6))
library(xtable)
print(xtable(df,digits=0, caption="Caption Left?"),include.colnames=TRUE, size = "small", comment=FALSE,   latex.environments="flushleft")
@
\end{document}

Which returns: enter image description here

like image 91
Robin Avatar answered Mar 15 '23 05:03

Robin


This operation is critical for anyone wishing to produce Markdown files in APA format since table captions are typically left-justified.

I'm going to clarify Robin's answer a little bit because, because totally new to the Markdown/Latex interface, it took me some time to figure out.

Upload the "caption" package (documentation available here) by including the

\usepackage{caption}

command in YAML (header) part of the document, preceded by

header-includes:

So an an entire YAML section at the header of the document might look like this:

---
title: "Supplementary Materials"
author: ""
date: "3/30/2018"
output:
  pdf_document: default
editor_options:
  chunk_output_type: inline
header-includes:
   - \usepackage{caption}

---

Then, at any point in the document, before a code chunk (in its own white space), you can insert the code:

\captionsetup{justification = raggedright, singlelinecheck = false}

To change the settings back again, you can re-insert this code at any point in white space of the Markdown file (not in a code chunk!)

E.g.

\captionsetup{justification = centering, singlelinecheck = false}
like image 41
Daniel Yudkin Avatar answered Mar 15 '23 06:03

Daniel Yudkin