Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knitr not aligning figures to center in pdf output--alternatives?

Tags:

r

pdf

rstudio

knitr

Using knitr to make pdfs, the figures don't show when using the fig.align='center' option:

require(knitr)
opts_chunk$set(fig.align='center') 

OR

```{r chunkname, fig.align='center'}
...code that makes figure...
```

Either way, no figures come out on the pdf when pressing the knit PDF button. But I remove the fig.align option and the figures appear, left aligned.

Tried it with fig_crop: false in the YAML header, too, same results.

This hints at why it's not working: https://github.com/rstudio/rmarkdown/issues/86 but it doesn't cover what to do instead if we need figures centered. I could just produce the plot as a png and import it with rmarkdown, but that is definitely not in the spirit of reproducible research!

Any ideas what to do?

## R version 3.1.1 (2014-07-10)
## Platform: x86_64-pc-linux-gnu (64-bit)
## RStudio Version 0.98.1028

(This is not a duplicate of Knitr: opts_chunk$set() not working in Rscript command)

like image 230
user3994188 Avatar asked Aug 31 '14 23:08

user3994188


2 Answers

This has been fixed in the development version of knitr, which I plan to release to CRAN in the next few days, and the version will be 1.8 if everything goes well with CRAN maintainers.

The reason for the original failure to align figures is that when fig.align is specified, the HTML syntax for images will be used (i.e. <img src=... style=... />), and Pandoc is unable to convert this to LaTeX properly. knitr 1.8 will just use raw LaTeX syntax to write figures, which will be preserved during the conversion from Markdown to LaTeX due to its raw_tex extension.

like image 198
Yihui Xie Avatar answered Jan 03 '23 18:01

Yihui Xie


As a workaround (see comment by Yihui) you could keep the .tex file and manually center the image:

\centering
\includegraphics[]{…}
like image 45
mrub Avatar answered Jan 03 '23 16:01

mrub