【问题标题】:How can I add a baseplot with no fixed values to a document如何将没有固定值的底图添加到文档中
【发布时间】:2020-11-01 00:14:03
【问题描述】:

我想在 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 的示例。

【问题讨论】:

  • 我猜“代码”在不同的环境中运行,因此无法访问定义的变量。 (虽然我不确定)所以一种可能有效的方法是将这些变量存储为 .rdata 对象并使用代码访问变量。这样您就可以在不引用之前定义的任何变量的情况下获取它们。然而,这是非常低效的,应该作为最后的手段。 (另外我实际上并没有测试它)
  • 问题是关于你代码中的名字xbody_add的第一个参数也是x...

标签: r officer


【解决方案1】:

我想我找到了解决办法!

当我在 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"))

【讨论】:

    【解决方案2】:

    代码产生如下错误

    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")
    

    【讨论】:

      猜你喜欢
      • 2013-06-13
      • 2011-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-16
      • 2013-04-04
      • 1970-01-01
      相关资源
      最近更新 更多