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

Viewed 63

I want to add a baseplot to a word document.

In the documentation for the officer package there's an example that uses the plot_instr function:

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

I want to add a plot to a word document inside a function so I need variable input for the plot function like this:

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

But the code above doesn't work and I can't find any other examples of plot_instr usage.

2 Answers

I think I found a solution!

When I set a breakpoint before the barplot(...) call, I could see the code when body_add is called with a plot_instr wrapper function. The code creates a temporary png file. I copied this code and adapted it:

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

The code is generating the following error

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

The issue here is that function body_add has an argument x and you are defining an x before the call. Changing the name to something else solves the issue:

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