[r] Centering image and text in R Markdown for a PDF report

I want to center an image and/or text using R Markdown and knit a PDF report out of it.

I have tried using:

->Text<-

->![](image1.jpg)<-

That does not do the trick! Any other way of getting this done?

This question is related to r markdown r-markdown

The answer is


I used the answer from Jonathan to google inserting images into LaTeX and if you would like to insert an image named image1.jpg and have it centered, your code might look like this in Rmarkdown

\begin{center}
\includegraphics{image1}
\end{center}

Keep in mind that LaTex is not asking for the file exention (.jpg). This question helped me get my answer. Thanks.


You can use raw LaTeX in R Markdown. Try this:

\begin{center}
Text
\end{center}

There is, of course, a catch: everything between begin{...} and \end{...} is interpreted as raw LaTeX by Pandoc, so you can't use this technique to center the output of R code chunks, or Markdown content.


I had the same question. I have tried all solutions provided above and none of them worked... But I have found a solution that works for me, and hopefully for others too.

<center>

![your image caption](image.png)

</center>

This code will center both the image and the caption. It is essential that you leave lines between <center>, the image code, and </center>, otherwise the image will be centered but the caption will disappear.

If you want your image to have a clickable link, you can embed things like

[![your image caption](image.png)](www.link_to_image.com)

However, the caption will no longer appear.

So if you want a clickable caption you will have to do it in two steps:

<center>

![](image.png)

[your image caption](www.link_to_image.com)

</center>

Same here, make sure there are empty lines in between each command ones. If you want both the image and the caption to be clickable, then combine the middle and the last codes above. I hope this helps a bit.


You can set the center (or other) alignment for the whole document as a Knitr option, using:

knitr::opts_chunk$set(echo = TRUE, fig.align="center")

none of the answers worked but this

\newcommand{\bcenter}{\begin{center}}
\newcommand{\ecenter}{\end{center}}

but then the following problem is that it works for only one figure and then will not for any other figures.

I just started learning R I knew it was going to be difficult but what's worst is that there is little to no info that I can refer to.


There is now a much better solution, a lot more elegant, based on fenced div, which have been implemented in pandoc, as explained here:

::: {.center data-latex=""}
Some text here...
:::

All you need to do is to change your css file accordingly. The following chunk for instance does the job:

```{cat, engine.opts = list(file = "style.css")}
.center {
  text-align: center;
}
``` 

(Obviously, you can also directly type the content of the chunk into your .css file...).
The tex file includes the proper centering commands.
The crucial advantage of this method is that it allows writing markdown code inside the block.
In my previous answer, r ctrFmt("Centered **text** in html and pdf!") does not bold for the word "text", but it would if inside a fenced div.

For images, etc... the lua filter is available here


The simple solution given by Jonathan works with a modification to cheat Pandoc. Instead of direct Latex commands such as

\begin{center}
Text
\end{center}

you can define your own commands in the YAML header:

header-includes:
- \newcommand{\bcenter}{\begin{center}}
- \newcommand{\ecenter}{\end{center}}

And then you use:

\bcenter
Text and more
\ecenter

This works for me for centering a whole document with many code chunks and markdown commands in between.


If you are centering the output of an R code chunk, e.g., a plot, then you can use the fig.align option in knitr.

```{r fig.align="center"}
plot(mtcars)
```

If you know your format is PDF, then I don't see how the HTML tag can be useful... It definitely does not seem to work for me. The other pure LaTeX solutions obviously work just fine. But the whole point of Markdown is not to do LaTeX but to allow for multiple format compilation I believe, including HTML.

Therefore, with this in mind, what works for me is a variation of Nicolas Hamilton's answer to Color Text Stackoverflow question:

#############
## CENTER TXT
ctrFmt = function(x){
  if(out_type == 'latex' || out_type == 'beamer')
    paste0("\\begin{center}\n", x, "\n\\end{center}")
  else if(out_type == 'html')
    paste0("<center>\n", x, "\n</center>")
  else
    x
}

I put this inside my initial setup chunk. Then I use it very easily in my .rmd file:

`r ctrFmt("Centered text in html and pdf!")`

None of the answers work for all output types the same way and others focus on figures plottet within the code chunk and not external images.

The include_graphics() function provides an easy solution. The only argument is the name of the file (with the relative path if it's in a subfolder). By setting echo to FALSE and fig.align=center you get the wished result.

```{r, echo=FALSE, fig.align='center'}
include_graphics("image.jpg")
```

Examples related to r

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R? R : how to simply repeat a command? session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium How to show code but hide output in RMarkdown? remove kernel on jupyter notebook Function to calculate R2 (R-squared) in R Center Plot title in ggplot2 R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph R multiple conditions in if statement What does "The following object is masked from 'package:xxx'" mean?

Examples related to markdown

How to add empty spaces into MD markdown readme on GitHub? how to make a new line in a jupyter markdown cell How do I display local image in markdown? How to markdown nested list items in Bitbucket? How to apply color in Markdown? How to right-align and justify-align in Markdown? Is there a way to add a gif to a Markdown file? How to add new line in Markdown presentation? How link to any local file with markdown syntax? How to insert a line break <br> in markdown

Examples related to r-markdown

How to show code but hide output in RMarkdown? How to add new line in Markdown presentation? R Markdown - changing font size and font type in html output How to add \newpage in Rmarkdown in a smart way? Insert picture/table in R Markdown Centering image and text in R Markdown for a PDF report Plot size and resolution with R markdown, knitr, pandoc, beamer Hiding the R code in Rmarkdown/knit and just showing the results R - Markdown avoiding package loading messages How to convert R Markdown to PDF?