Dan*_*eks 5 pdf markdown plot r knitr
将 R Markdown 文档排版为 PDF 时,如果一个函数绘制多个绘图,这些绘图通常并排显示,只有第一个绘图完全位于页面的边距内。
最小 R Markdown 示例:
---
title: "Example re plotting problem"
author: "Daniel E. Weeks"
date: "May 3, 2016"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Multiple plots within a loop
```{r}
plots <- function() {
plot(rnorm(100))
hist(rnorm(100))
}
for (i in 1:3) {
plots()
}
```
Run Code Online (Sandbox Code Playgroud)
这是生成的 PDF 的第 2 页的屏幕截图
这显示了问题。我在网上搜索过,但还没有找到解决这个问题的方法。
谢谢你。
user2554330 提出的 plot hook 解决方案很简单,效果很好。因此,此代码在生成的 PDF 的边距内绘制所有图:
---
title: "Example re plotting problem"
author: "Daniel E. Weeks"
date: "May 3, 2016"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Multiple plots within a loop
```{r}
plots <- function() {
plot(rnorm(100))
hist(rnorm(100))
}
```
## Call plotting function
```{r}
my_plot_hook <- function(x, options)
paste("\n", knitr::hook_plot_tex(x, options), "\n")
knitr::knit_hooks$set(plot = my_plot_hook)
for (i in 1:3) {
plots()
}
```
Run Code Online (Sandbox Code Playgroud)
The problem is that the generated .tex file has no spaces between the \includegraphics{} calls. LaTeX gives warnings about overfull hboxes, because the graphics aren't big enough to sit alone on a line, and are too big when it puts two on each line.
您可以通过添加告诉 LaTeX(实际上是 TeX)输出坏行,而无需在每行上放置两个数字
\pretolerance=10000
Run Code Online (Sandbox Code Playgroud)
在代码块之前的文本中。您可能希望将其设置回其默认值
\pretolerance=100
Run Code Online (Sandbox Code Playgroud)
在代码块之后,或者 LaTeX 之后不会尝试断字,并且文本看起来非常难看。
解决此问题的另一种方法是强制每个数字都在自己的段落中。您可以通过添加此代码来做到这一点
my_plot_hook <- function(x, options)
paste("\n", knitr::hook_plot_tex(x, options), "\n")
knitr::knit_hooks$set(plot = my_plot_hook)
Run Code Online (Sandbox Code Playgroud)
在进行绘图之前放入代码块。这会在每个数字之前和之后放置一个空行。