如何将没有固定值的底图添加到文档中

How can I add a baseplot with no fixed values to a document

我想在word文档中添加底图。

在 officer 包的文档中有一个使用 plot_instr 函数的示例:

anyplot <- plot_instr(code = {
  barplot(1:5, col = 2:6)
  })

doc <- read_docx()
doc <- body_add(doc, anyplot, width = 5, height = 4)
print(doc, target = tempfile(fileext = ".docx"))

我想在一个函数内向 word 文档添加一个绘图,所以我需要像这样的绘图函数的变量输入:

x=1:5
cols=2:6
anyplot <- plot_instr(code = {
    barplot(x,col=cols)
})

doc <- read_docx()
doc <- body_add(doc, anyplot, width = 5, height = 4)
print(doc, target = tempfile(fileext = ".docx"))

但是上面的代码不起作用,我找不到任何其他 plot_instr 用法的例子。

我想我找到了解决办法!

当我在 barplot(...) 调用之前设置断点时,我可以看到使用 plot_instr 包装函数调用 body_add 时的代码。该代码创建一个临时 png 文件。我复制并修改了这段代码:

x=1:5
cols=2:6

doc <- read_docx()

file <- tempfile(fileext = ".png")
options(bitmapType = "cairo")
png(filename = file, width = 5, height = 5, units = "in", res = 300)
tryCatch({
  barplot(x,col=cols)
}, finally = {
  dev.off()
})
on.exit(unlink(file))
value <- external_img(src = file, width = 5, height = 5)
body_add(doc, value)

print(doc, target = tempfile(fileext = ".docx"))

代码生成以下错误

Error in barplot.default(x, col = cols) : 
  'height' must be a vector or a matrix 

这里的问题是函数 body_add 有一个参数 x 并且您在调用之前定义了一个 x 。将名称更改为其他名称可解决问题:

z <- 1:5
cols=2:6
anyplot <- plot_instr(code = {
  barplot(z, col = cols)
})

doc <- read_docx()
doc <- body_add(doc, anyplot, width = 5, height = 4)
print(doc, target = "temp.docx")