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)
```
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.
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.
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" .
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.
On the LaTeX side, a vertically centered figure must be a figure
with position p
. How this can be achieved using knitr
depends:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With