Search code examples
rofficerrvg

Export R base graphics using rvg to PowerPoint


I am trying to use the officer package in order to produce a PowerPoint document that contains R base graphics, preferably not with fixed resolution, but rather as editable vector graphics. Here is what I have been trying, but the resulting PowerPoint document still lacks the diagram (the intermediate .dml was created and contains some XML).

library (officer)
library (rvg)

# write an R base graphics plot to "plot.dml"
dml_pptx ("plot.dml")
x = (-300:300)/100
plot (x,sin(x),type="l",col="blue")
dev.off ()

# create a PowerPoint document
doc = read_pptx ()
doc = add_slide (doc,layout ="Title and Content",master="Office Theme")
ph_with (doc,external_img (src="plot.dml"),location=ph_location_type(type="body"))
print (doc,"example.pptx")

When I instead generate the graphics file by jpeg ("plot.jpg") and then include that file in the presentation, it works, but I'd like to avoid a fixed resolution and have the diagram editable in PowerPoint.

An alternative strategy might be the export package,

library (export)

x = (-300:300)/100
plot (x,sin(x),type="l",col="blue")

graph2ppt (file="example2.pptx",width=6,height=6)

The latter works interactively, but fails in a script. What am I missing?

Thanks in advance for your help.

HPF


Solution

  • You need to use argument code of function dml and provide an expression containing your plot instructions:

    library(rvg)
    library(officer)
    library(magrittr)
    read_pptx() %>% 
      add_slide(layout = "Title and Content", master = "Office Theme") %>% 
      ph_with(dml(code = {
        x = (-300:300)/100
        plot (x,sin(x),type="l",col="blue")
      }), location = ph_location_type(type = "body")) %>% 
      print(target = "demo_rvg.pptx")