如何在 knitr 的 pdf 输出中用图形标题保持图形位置?

How to hold figure position with figure caption in pdf output of knitr?

我正在使用 knitr(1.9.5 和 1.9.17)和 rmarkdown(0.5.3.1),并希望在 pdf 输出中保留图形位置。使用块选项 fig.pos="H" 时,生成的 pdf 文件工作正常。

但是在设置fig_caption: yes时图形位置不保持 yaml header.

我该如何解决这个问题?感谢您的任何建议。

编辑:

学习了Latex的浮动环境后。我将 float 包添加到 header.

\usepackage{float}

但是生成的 tex 文件总是在 figure 环境中使用 htbp,因为使用了任何 fig.pos 选项。手动将htbp改为H后,所有数字的位置都保持不变

这是我的 rmd 文件示例:

---
title: "Untitled"
output:
  pdf_document:
    fig_caption: yes
    includes:
        in_header: mystyles.sty
---

# Section 1


Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.

Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.

Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.

Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.


```{r fig1, echo=FALSE, fig.height=8.5, fig.pos="H"}
plot(cars)
```

# Section 2

More test

```{r fig2, echo=FALSE, fig.height=8.5, fig.pos="H"}
plot(cars)
```

# Section 3

```{r fig3, echo=FALSE, fig.height=8.5, fig.pos="H"}
plot(cars)
```

More test

正如一辉在他的回答中提到的(Figure position in markdown when converting to PDF with knitr and pandoc),我们不能对 mardown 的格式化抱有太大期望。要解决此问题,只需编写一些 R 脚本将 htbp 替换为 H

与 knitr 包中的 knit 相比,我发现 rmarkdown 中的 render 更适合导出 tex 文件。请记住在 rmarkdown 文件的 yaml header 中添加 keep_tex: yes

library(rmarkdown)
render('filepath.Rmd')
x <- readLines('filepath.tex')
pos <- grep('begin\{figure\}\[htbp\]', x)
x[pos] <- gsub('htbp', 'H', x[pos])
writeLines(x, 'filepath.tex')
tools::texi2pdf('filepath.tex', clean = TRUE)  # gives foo.pdf

file.remove('filepath.tex')

更新看看这个更好的解决方案here。 (下面的问题总结还是不错的,不过跟着link会有更好的解决办法)。

总结RStudio中的一些测试

只要 fig_caption: yes 不在 yaml header.

中,knitr 块参数 fig.pos = "H" 就可以工作

生成的 .tex 中的每个图形看起来像这样

\subsection{my_section}\label{my_section}

\includegraphics{path_to_fig.pdf}

但是如果 fig_caption: yes 在 yaml header 中,那么 .tex 看起来像这样

\subsection{my_section}\label{my_section}

\begin{figure}[htbp]
\centering
\includegraphics{path_to_fig.pdf}
\caption{}
\end{figure}

fig.pos = "H"没用过,"htbp"有。

使用 RStudio 的解决方法:

fig_caption: yes
keep_tex: yes

在 yaml 中以及

header-includes: \usepackage{float}

然后在生成的.tex文件中搜索并替换[htbp][H]

然后在 RStudio 中打开 .tex 文件并使用 "Compile PDF" 按钮。


示例.Rmd

---
title: "Testing fig placement with captions"
author: "Andrew Dolman"
date: "1 September 2015"
output: 
  pdf_document: 
    fig_caption: yes
    keep_tex: yes
header-includes: \usepackage{float}
---

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

```{r}
summary(cars)
```

You can also embed plots, for example:

```{r, echo=FALSE, fig.pos="H"}
plot(cars)
```

Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.

```{r, echo=FALSE, fig.pos="H"}
plot(cars)
```

正如 Andrew 所指出的,这个 fig.pos 在块中不起作用,但如果将它放在全局选项中它确实有效:

```{r global_options, include=FALSE}
knitr::opts_chunk$set(fig.pos = 'H')
```

编辑: 以上显然用于工作并且在序言中需要 \usepackage{float}

header-includes:
 \usepackage{float}

另请参阅 here and the Cookbook 了解其他一些方法。

虽然@Bangyou提供的答案有效,但是编起来比较复杂

您还可以在 Latex 中设置图形放置的全局默认选项,包括在 YAML 中 header 包括:

\makeatletter\renewcommand*{\fps@figure}{H}\makeatother

正如 here (and here\makeat... 部分的解释。

这样你就可以在 RStudio 或 rmarkdown::render 中使用编织按钮并完成它。

问题是,所有数字都强制填充 H,您将无法将其设置为浮动。

对我有用的选项:

在开头的.tex中:\usepackage{float}.

Rmd 开头:knitr::opts_chunk$set(fig.pos = 'H')。大写的H).

并且在每个带有图像的块中:fig.cap="lorem blabla"out.extra=''(参数值=空字符串)。

需要定义: fig_caption: yeskeep_tex: yes 在 yaml 中。

这些选项使图像保持其位置,无论是对于 include_graphics 还是由 R 代码生成的图。

我在 bookdown 环境中使用了它们,按预期生成了 pdf 和 html :)

对我来说,添加 float 包然后在 YAML 中添加 \floatplacement{figure}{H} 解决了这个问题,如:

---
title: "test"
date: "`r Sys.Date()`"
output: 
  pdf_document :
    keep_tex: true
    number_sections: true
header-includes:
 \usepackage{booktabs}
 \usepackage{longtable}
 \usepackage{array}
 \usepackage{multirow}
 \usepackage[table]{xcolor}
 \usepackage{wrapfig}
 \usepackage{float}
 \floatplacement{figure}{H}
---

Figure position in markdown when converting to PDF with knitr and pandoc 中的代码帮助了我,帮助其他人发现它有用。

---
title: "Example"
author: "Martin"
output: pdf_document
---

```{r}
knitr::knit_hooks$set(plot = function(x, options)  {
  knitr::hook_plot_tex(x, options)
})
```


```{r myplot, echo=FALSE, results='hide', fig.cap='Test', fig.pos='h'}
library(ggplot2)
ggplot(mtcars, aes(mpg, drat)) + geom_point()
```