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

10,691

Solution 1

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.

Solution 2

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

\centering
\includegraphics[]{…}
Share:
10,691
Admin
Author by

Admin

Updated on June 13, 2022

Comments

  • Admin
    Admin almost 2 years

    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)

  • Yihui Xie
    Yihui Xie over 9 years
    Thanks, but we certainly want an automatic solution :) I'm working on this now.
  • mrub
    mrub over 9 years
    I certainly agree (I also stumbled on this bug), but since it is unclear when to expect the fix (I can only rely on skilled coders like you) it might be nice to have an immediate solution.
  • Heather Turner
    Heather Turner over 9 years
    note this requires the graphicx LaTeX package, which can be included as described here tex.stackexchange.com/a/211638/21118