rggplot2dpiofficer

How to increase resolution of ggplots without using ggsave in officer?


I'm using officer to automate powerpoint slides that contain ggplots. Unfortunately, the default resolution is poor. I saw a previous question from 6 years ago suggest using ph_with_vg(), but that function isn't in the current version. In that same question, it was recommended to use dml(), but that also won't work in my case because after I export the slides to PowerPoint, I immediately convert them to Google Slides using the googledrive package. In that conversion, the formatting gets misaligned.

Last, I know you can increase the dpi / resolution by using ggsave(), but with the number of plots I need, it drastically slows things down to save each file and then read them back in.

Is there a solution that does not force ggsave?

library(tidyverse)
library(officer)

sample_plot <- ggplot(mtcars, aes(x = hp)) +
  geom_histogram()

template <- read_pptx()

so_deck <- template %>%
  add_slide(layout = 'Title and Content', master = 'Office Theme') %>%
  ph_with(value = sample_plot,
          location = ph_location_type("body"))

print(so_deck, "stack overflow test.pptx")

Solution

  • You can set the resolution via the res= argument of ph_with.gg which (see ?ph_with) sets the

    resolution of the png image in ppi

    library(tidyverse)
    library(officer)
    
    sample_plot <- ggplot(mtcars, aes(x = hp)) +
      geom_histogram()
    
    template <- read_pptx()
    
    so_deck <- template %>%
      add_slide(layout = "Title and Content", master = "Office Theme") %>%
      ph_with(
        value = sample_plot,
        location = ph_location_type("body"),
        res = 1200
      )
    
    print(so_deck, "so-test-res-1200.pptx")