Adding space around figures in RMarkdown

2020-06-23 09:24发布

问题:

I would like to add space around figures in RMarkdown. I am knitting to PDF and really don't like how close figures (or also equations) are to the text or to the next figure.

---
output: pdf_document
---

```{r pressure, echo=FALSE}
plot(pressure)
```

```{r pressure2, echo=FALSE}
plot(pressure)
```

There is just too little space between the two plots and this gets more fuzzy when using ggplots.

Right now I use the Latex solution

\vspace{10pt}

but it would be nice if I could make a setting globally for the entire document.

回答1:

Concerning the spacing before and after plots you can use a simple knitr hook:

```{r, echo = F}
library(knitr)
if(is_latex_output()) {
  plot_default <- knit_hooks$get("plot")
  knit_hooks$set(plot = function(x, options) { 
    x <- c(plot_default(x, options), "\\vspace{25pt}")
  })
}
```

Here we alter the plot hook in that sense that we just add a spacing of 25pt after each plot output.

Concerning equations you can just add these four length definitions at the beginning of your document:

\setlength{\abovedisplayskip}{25pt}
\setlength{\belowdisplayskip}{25pt}
\setlength{\abovedisplayshortskip}{25pt}
\setlength{\belowdisplayshortskip}{25pt}

The first two alter equations created using the align environment. The latter two those created using $$ ... $$.