Next Door Engineer
Next Door Engineer

Reputation: 2886

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?

Upvotes: 89

Views: 203992

Answers (16)

Fran
Fran

Reputation: 264

---
output: pdf_document
---

Some text

![your image caption](example-image.png){width="20%" align="center"}

More text

wme

This work also in the newer Quarto format but using format: pdf instead of output: pdf_document in the YAML header and saving the file with the .qmd extension instead of .Rmd.

I should point out that this works with figures with captions. What you have without a caption is a non-floating inline image; therefore, it cannot be aligned (is just like a text character).

However, for images without caption (or plain text) you can use:

::: {.center data-latex=""}

stuff to be centred

:::

This is better than a raw LaTeX center environment, since you can use markdown code inside.

With Quarto (not for Rmarkdown) for figures (no just images) you can also put the image into a block with the label #fig-whatever and will be automatically centred. Note that the caption could be in Quarto in the block options or after the image in a single paragraph (any text above the last paragraph will be treated as part of the figure and centred too). The MWE below summarizes these options with images and figures:

enter image description here

---
format: pdf
---

![](example-image){width=10% align="center"}

\dotfill

::: {.center data-latex=""}

![](example-image){width=10%}

:::

\dotfill

![foo](example-image){width=10%}

\dotfill

::: {#fig-foo fig-cap="foo"}

![](example-image){width=10%}

:::

\dotfill

::: {#fig-foo}

![](example-image){width=10%}

foo 
:::

\dotfill

Edited to respond to a comment

To centre a plot created in a code chunk in Quarto, use the same knitr option as in Rmarkdown, but with the Quarto syntax: fig-align: center

mwe2

To compile the above image was used this MWE:

---
format: pdf
---

{{< lipsum 1 >}}

```{r}
#| fig-width: 2
#| fig-align: center
#| echo: false

plot(1:10)

```

{{< lipsum 1 >}}

Upvotes: 0

sparsh gupta
sparsh gupta

Reputation: 1

Hey here is the simple way which I found recently.

\center

image

\raggedright

text

This code worked for pdf file in the R markdown.

Upvotes: 0

Douwe
Douwe

Reputation: 122

Since the question asks for both text and image alignment and I had a hard time finding an option for text that worked, with non of the ones above working withing a code chunk (for me). I wanted to share this: it seem to do the trick to the best of it's abilities (meaning it's not perfectly centered but close)

centerText <- function() {
  width <- getOption("width")
  out <- "your text"
  ws <- rep(" ", floor((width - nchar(out))/2))
  cat(ws, out, sep = "")
}
centerText()  

Original code comes from here

Upvotes: 0

Jos&#233; Guijarro
Jos&#233; Guijarro

Reputation: 1

None of these solutions worked for me when inserting a pdf figure in the text. After intensive trial and error, what made the trick for me (for a pdf output) was:

\hfil ![](image1.pdf) \hfil

Upvotes: 0

Regnier
Regnier

Reputation: 11

Just to update the question. To do this some easy way, you can add fig.align="center" to the chunk with the chuck knitr options:

    knitr::opts_chunk$set(echo = TRUE,
                          fig.align="center" #align all the figures in the center
                          )

Upvotes: 1

Fran&#231;ois Birgand
Fran&#231;ois Birgand

Reputation: 1019

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.

Upvotes: 95

igorkf
igorkf

Reputation: 3565

I'm using beamer to knit pdf from Rmarkdown and what worked for me is:

\centering
![](image1.jpg)

Upvotes: 8

J.E. C
J.E. C

Reputation: 1

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.

Upvotes: 0

tchevrier
tchevrier

Reputation: 1171

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

Upvotes: 4

j3ypi
j3ypi

Reputation: 1557

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")
```

Upvotes: 20

JuergenL
JuergenL

Reputation: 161

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.

Upvotes: 10

tchevrier
tchevrier

Reputation: 1171

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!")`

Upvotes: 4

Antonio Canepa
Antonio Canepa

Reputation: 317

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")

Upvotes: 21

Lincoln Mullen
Lincoln Mullen

Reputation: 6455

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)
```

Upvotes: 77

cylondude
cylondude

Reputation: 1888

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.

Upvotes: 12

Jonathan
Jonathan

Reputation: 8812

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.

Upvotes: 28

Related Questions