如何在knitr中使用不同的“ dev.off()”(自动裁剪图形)

时间:2019-03-21 17:50:44

标签: knitr rnw

我想在将pdf()转换为PDF的.Rnw文档中使用自己的knitr绘图设备。生成图的PDF之后 它应该调用pdfCrop.off()而不是dev.off()(或任何knitr调用);这个会 完美裁剪所得的数字。该怎么办?

如果注释了(*)(以及正确关闭的行),则以下MWE可以工作(但不会裁剪)。

\documentclass{article}

\begin{document}
<<knitr_options, echo = FALSE, results = "hide", purl = FALSE>>=
## Custom graphics device (for cropping .pdf):
pdfCrop <- function(file, width, height, ...)
{
    f <- file
    grDevices::pdf(f, width = width, height = height, onefile = FALSE)
    assign(".pdfCrop.file", f, envir = globalenv())
}
pdfCrop.off <- function() # used automagically
{
    grDevices::dev.off() # closing the pdf device
    f <- get(".pdfCrop.file", envir = globalenv())
    system(paste("pdfcrop --pdftexcmd pdftex", f, f, "1>/dev/null 2>&1"),
           intern = FALSE) # crop the file (relies on PATH)
}

## knitr options
knitr::opts_chunk$set(fig.path = "./fig_", background = "#FFFFFF",
                      dev = "pdfCrop", fig.ext = "pdf") # (*) => how to use pdfCrop.off() instead of dev.off()?
@

<<MWE>>=
<<fig-MWE, eval = FALSE, echo = FALSE>>=
plot(1:10, 10:1)
@
\setkeys{Gin}{width=\textwidth}
\begin{figure}[htbp]
  \centering
  \framebox{
<<figMWE, echo = FALSE, fig.width=6, fig.height=6>>=
<<fig-MWE>>
@
}
\caption{Just some text to show the actual textwidth in order to see that the
  figure is not perfectly horizontally aligned due to some white space which can
  be avoided by properly crop the figure with an adequate pdf crop device.}
\end{figure}

\end{document}

1 个答案:

答案 0 :(得分:0)

knitr已经提供了基于pdfcrop的裁剪设备,因此我们可以通过钩子使用它:

\documentclass{article}

\begin{document}
<<knitr_options, echo = FALSE, results = "hide", purl = FALSE>>=
## knitr options
library(knitr)
knit_hooks$set(crop = hook_pdfcrop)
knitr::opts_chunk$set(fig.path = "./fig_", # all figures are saved as fig_*
                      background = "#FFFFFF", # avoid color
                      crop = TRUE) # always crop
@

<<MWE>>=
<<fig-MWE, eval = FALSE, echo = FALSE>>=
plot(1:10, 10:1)
@
\setkeys{Gin}{width=\textwidth}
\begin{figure}[htbp]
  \centering
<<figMWE, echo = FALSE, fig.width=6, fig.height=6>>=
<<fig-MWE>>
@
\caption{Just some text to show the actual textwidth in order to see that the
  figure is not perfectly horizontally aligned due to some white space which can
  be avoided by properly crop the figure with an adequate pdf crop device.}
\end{figure}

\end{document}