Search code examples
rggplot2officer

How to increase resolution of ggplots when exporting using officer R


I want to export charts to a PPT and am using the officer package to achieve the same. However, the default resolution of the charts is low and I would like to change that. I am currently using the following call

    ph_with_gg(p1,type = "chart",res = 1200)

where p1 is a ggplot object. On running this, I get the following error:

    Error in png(filename = file, width = width, height = height, units = 
"in",  : 
  formal argument "res" matched by multiple actual arguments

Would really appreciate the help around this


Solution

  • Rather than using png, for high-resolution plots in PPT you should be using vector graphics.

    See under extensions:

    Vector graphics with package rvg

    The package rvg brings an API to produce nice vector graphics that can be embedded in PowerPoint documents or Excel workbooks with officer.

    This package provides functions dml() and ph_with() corresponding method to export ggplots to .pptx as vector graphics.

    Example:

    library(ggplot2)
    library(officer)
    library(rvg)
    library(magrittr)
    data(iris)
    
    read_pptx() %>%
      add_slide(layout='Title and Content',master='Office Theme') %>%
      ph_with('Iris Sepal Dimensions', location = ph_location_type(type="title")) %>%
      ph_with(dml( ggobj=
                     ggplot(iris, aes(x=Sepal.Length,y=Sepal.Width,col=Species)) +
                     geom_point()), location = ph_location_type(type="body")) %>%
      print('iris_presentation.pptx')
    

    As an additional benefit, you will be able to edit the charts in PowerPoint. For example, if you decided to capitalize the names of the 3 species, you could just edit the chart instead of editing the data and regenerating the slides. (You can also make the plots non-editable, but editable is the default.)