rplotofficer

Use a recorded plot for officer


To export a base R plot with officer, you have to wrap its code into plt_instr:

doc <- read_docx()

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

doc <- body_add_plot(doc, value = p, style = "centered")

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

However, there is a way to save a base R plot to an object using recordPlot:

plot(1:10)
p2 <- recordPlot()

Is there a way to pass this object to the body_add_plot function instead of wrapping the code with plot_instr?


Solution

  • You could use replayPlot().

    Seems to work fine.

    library(officer)
    
    doc <- read_docx()
    
    p <- plot_instr(barplot(1:5, col = 2:6))
    doc <- body_add_plot(doc, value = p, style = "centered")
    
    plot(1:10)
    p2 <- recordPlot()
    doc <- body_add_plot(doc, value = replayPlot(p2), style = "centered")
    
    f <- print(doc, target = tempfile(fileext = ".docx"))
    open_file(f)