rggplot2plotpowerpointr-commander

Exporting a multigraph from ggplot to powerpoint with officer


somehow I am not able to properly export a plot containing three subplots into my PowerPoint with the officer package. I will most an MWE with the same but different data that produces the plot that I want to export

library(fpp3)
library(officer)
library(rvg)


p1 <- global_economy %>%
  filter(Code == "CAF") %>%
  gg_tsdisplay(difference(Exports), plot_type='partial')


#PPT
p_dml <- rvg::dml(ggobj = p1, editable = F)

my_pres <- read_pptx("...path/presentation.pptx")
my_pres <- add_slide(my_pres,layout = "Headline 1-zeilig", master = "Master-Design") #should be adjusted 
my_pres<- ph_with(my_pres, value = p_dml , location = ph_location_fullsize())

print(my_pres, target = "...path/presentation.pptx") 

This is the graph that I am producing inside R:

enter image description here

But in the final PowerPoint only the lower right figure is displayed and not all three graphs.


Solution

  • The issue is that the object returned by gg_tsdisplay is not a ggplot object but a list of ggplot objects instead. As a consequence only the last element of this list is exported to the pptx or you get an error in the case where your first convert to a dml object.

    One possible fix would be to build your multi plot using the patchwork package which as a side effect will "convert" the list of plots to a ggplot object. After doing so you could easily export to pptx whether as a ggplot object or as an dml object. In my code below I use patchwork::wrap_plots and use the design argument to mimic the layout of your multi plot:

    library(fpp3)
    library(officer)
    library(rvg)
    
    p1 <- global_economy %>%
      filter(Code == "CAF") %>%
      gg_tsdisplay(difference(Exports), plot_type='partial')
    
    library(patchwork)
    
    p1 <- p1 |>
      wrap_plots(design = "AA\nBC")
    
    p_dml <- rvg::dml(ggobj = p1, editable = F)
    
    my_pres <- read_pptx()
    my_pres <- add_slide(my_pres,layout = "Title and Content", master = "Office Theme")
    my_pres<- ph_with(my_pres, value = p_dml, location = ph_location_fullsize())
    
    print(my_pres, target = "presentation.pptx")
    

    enter image description here