如何在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文件工作正常.
I am using knitr (1.9.5 and 1.9.17) and rmarkdown (0.5.3.1), and would like to hold figure position in the pdf output. The generated pdf file is working fine when chunk option fig.pos="H"
is used.
但是,如果在fig_caption: yes
中设置了fig_caption: yes
,则图形位置不保持.
yaml标头.
However, the figure position is not hold when fig_caption: yes
is set in the
yaml header.
我应该如何解决此问题?感谢您的任何建议.
How should I fix this problem? Thanks for any suggestions.
学习了Latex的浮动环境之后.我将float
包添加到标题中.
After learning the float environment of Latex. I add float
package into header.
\usepackage{float}
但是考虑到使用了任何fig.pos
选项,在figure
环境中生成的tex文件始终使用htbp
.手动将htbp
更改为H
后,所有图形的位置都将保留.
But the generated tex file always use htbp
in the figure
environment regard to any fig.pos
options are used. After manually changing htbp
to H
, positions of all figures are hold.
这是我的rmd文件示例:
This is my example of rmd file:
---
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
推荐答案
As Yihui mentioned in his answer (Figure position in markdown when converting to PDF with knitr and pandoc), we cannot expect too much about formatting from mardown. To workaround this problem, just write some R scripts to replace htbp
to H
.
与knitr包中的knit
相比,我发现rmarkdown中的render
更好地导出了tex
文件.只需记住在rmarkdown文件的yaml标头中添加keep_tex: yes
.
Compared with knit
from knitr package, I found render
from rmarkdown is better to export a tex
file. Just remember to add keep_tex: yes
in the yaml header of your rmarkdown file.
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')
这篇关于如何在Knitr的pdf输出中使用图形标题保持图形位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!