问题描述
我使用 knitr::knit_engines$set()
为 knitr 创建了一个自定义块引擎,它采用一些 YAML 规范,解释它们,并创建一个绘图作为输出。如果 knitr 文档呈现为 HTML,我会创建闪亮的输出,我使用 htmltools::knit_print.shiny.tag()
将其转换为 HTML,并且效果很好。但是,如果我渲染为 pdf/docx/odf,我会创建一个静态绘图对象而不是闪亮的输出。这一点很好,但我只能让它渲染图的文本表示(即列表对象),而不是图的图像。
我需要以某种方式将图像(我假设)传递给 knitr::knit_engines$set() 的输出,但是如果我尝试将绘图保存为 png,然后将其作为输出传递,我只会得到文本表示代替文件路径。
knitr::knit_engines$set(example = function(options) {
#### read options$code and do stuff - works fine
p <- ggplot(data = mpg) + geom_jitter(aes(x = cty,y = hwy))
##### output results
# Shiny - outputs html text. Works fine
if(knitr::opts_knit$get("rmarkdown.pandoc.to") == "html"){
shiny::plotOutput(p) %>%
htmltools::knit_print.shiny.tag()
# Static output formats (pdf,etc)
} else {
#### attempt 1 ####
p # returns list object
#### attempt 2 ####
ggsave(filename = here("temp","out.png"),plot = p)
knitr::include_graphics(here("temp","out.png")) # Returns here("temp","out.png")
}
})
我已经浏览了 Github 上的 knitr/R/engine.R 以获得灵感,但只是迷失了方向。
解决方法
这个“失败”的原因是 knitr::include_graphics()
以这种方式工作:它返回一个 structure
包含路径(和一些额外的参数),在 PDF/LaTeX 输出的情况下,结果在正在打印的路径中。
相反,您需要通过 knitr::engine_output
将结构传递给输出钩子:
imgpath <- here("temp","out.pdf")
ggsave(plot = p,filename = imgpath,device = "pdf",width = 15,height = 8,units = "cm")
knitr::engine_output(
options,out = list(knitr::include_graphics(imgpath))
)
(请注意,我将图像另存为 PDF,我发现它比光栅图像更易于处理。)
```{example}
This is your example engine chunk.
```