Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centre a plot to the middle of a page using Knitr

Tags:

r

pdf

rstudio

knitr

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)

```
like image 701
Damian Avatar asked Nov 25 '15 17:11

Damian


People also ask

How do I center a plot in R markdown?

To center an image using the knitr::include_graphics() function, include it within an R code chunk that has the fig. align='center' option (and perhaps other options to control width, etc.). For example: Be sure to include the echo = FALSE chunk option to prevent the chunk source code from being printed.

How do I center an output in R?

The option for centering a plot you generated by R code in Rmd file and that for an existing figure from a file elsewhere is different. For the figures you generated in R, I think fig. align="center" is sufficient, even if you want a PDF output. For <center> <\center> to work, you can only use an HTML output.

How do I center a title in R markdown?

To center images, text, and anything else in Github markdown and READMEs simply wrap the element in an HTML tag with the align attribute set to "center" .

What is the purpose of knitr?

The purpose of knitr is to allow reproducible research in R through the means of literate programming. It is licensed under the GNU General Public License. knitr was inspired by Sweave and written with a different design for better modularization, so it is easier to maintain and extend.


1 Answers

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.

like image 137
CL. Avatar answered Oct 19 '22 23:10

CL.