Centre a plot to the middle of a page using Knitr

38,341

On the LaTeX side, a vertically centered figure must be a figure with position p. How this can be achieved using knitr depends:

  • If the figure has a caption, it is placed in a figure environment (see fig.env). Then only the additional option fig.pos = 'p' is needed.
  • If the figure has no caption (which is usually bad), you can manually add the figure environment:

    \begin{figure}[p]
    
    ```{r,fig.align='center',out.extra='angle=90', echo=FALSE}
    
    library(ggplot2)
    ggplot(diamonds, aes(y=carat, x=price, colour=clarity))+geom_point()+
    facet_wrap(~cut)
    
    ```
    \end{figure}
    

Note that this works when compiling to PDF but restricts you to PDF as output format.

Share:
38,341
Damian
Author by

Damian

Neuroscientist at Columbia University

Updated on July 21, 2022

Comments

  • Damian
    Damian almost 2 years

    I'd like to align a plot to the center of a page of a knitr-generated pdf document. I can horizontally align the plot to the center using fig.align='center' but can't figure out how to get the plot vertically aligned to the center.

    I've been using the following code:

    ---
    header-includes: \usepackage{graphicx}
    output: 
      pdf_document
    geometry:
      left=1in,right=1in,top=1in,bottom=1in
    ---
    
    
    ```{r,fig.align='center',out.extra='angle=90', echo=FALSE}
    
    library(ggplot2)
    ggplot(diamonds, aes(y=carat, x=price, colour=clarity))+geom_point()+
    facet_wrap(~cut)
    
    ```
    
  • nad7wf
    nad7wf over 3 years
    I've spent several days (literally) trying to figure out how to knit a pdf with many images, but have only one image per page and vertically centered. I finally came across your solution for a single figure, but I'm having trouble adapting it for many images. Please help! :)
  • CL.
    CL. over 3 years
    @nad7wf Have a look at this gist; I think it might solve your problem. If not, please open a new question (and ping me here so I get a notification). Hope that helps!