Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increase resolution of ggplots when exporting using officer R

Tags:

r

ggplot2

officer

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

like image 908
Nishant Kachawa Avatar asked Oct 27 '25 13:10

Nishant Kachawa


2 Answers

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.)

like image 119
C8H10N4O2 Avatar answered Oct 29 '25 02:10

C8H10N4O2


Is it important that the plot is saved to a presentation in the code?

Otherwise using:

ggsave(filename = file, p1, width = width, height = height, dpi = dpi)

will give you a png of any resolution you need..

(provided that filename ends with .png and you set width, height and dpi to appropriate values)

like image 33
frostell Avatar answered Oct 29 '25 02:10

frostell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!