Search code examples
rgridextraofficer

r - Why can't I send a group of plots in a grid to PowerPoint with officer?


I've created a grid of qicharts2 plots using gridextra but when I try to send it to PowerPoint using officer I get this error..

Error in doc_parse_raw(x, encoding = encoding, base_url = base_url, as_html = as_html, : StartTag: invalid element name [68]

This is my code:

library(qicharts2)
library(gridExtra)
library(officer)
library(rvg)



#24 random numbers from a normal distribution for example.
y1 <- rnorm(24)
y2 <- rnorm(24)

yC1 <- qic(y1)
yC2 <- qic(y2)

grid <- grid.arrange(yC1,yC2)


filename <- "C:\\Desktop\\MyCharts.pptx"


read_pptx(filename) %>% 

  add_slide(layout = "Title and Content", master = "Office Theme") %>% 
  ph_with_vg(code = print(grid), type = "body") %>% 
  print(target = filename) %>% 
  invisible()

Huge thanks to everyone for your advice on how to improve my question so far.

Any help further help greatly received


Solution

  • When using grid.arrange, you are plotting, the print method is not useful here (print(grid) had no effect on graphical device). The following is working with grid.arrange:

    library(qicharts2)
    library(gridExtra)
    library(officer)
    library(rvg)
    library(magrittr)
    
    #24 random numbers from a normal distribution for example.
    y1 <- rnorm(24)
    y2 <- rnorm(24)
    
    yC1 <- qic(y1)
    yC2 <- qic(y2)
    
    read_pptx() %>% 
      add_slide(layout = "Title and Content", master = "Office Theme") %>% 
      ph_with_vg(code = grid.arrange(yC1,yC2), type = "body") %>% 
      print(target = "filename.pptx") %>% 
      browseURL()
    

    Edit for rvg >= 0.2.4 : You must use the dml function :

    read_pptx() %>% 
      add_slide(layout = "Title and Content", master = "Office Theme") %>% 
      ph_with(value = dml(grid.arrange(yC1,yC2)), location = ph_location_type(type = "body")) %>% 
      print(target = "filename.pptx") %>% 
      browseURL()