How to increase resolution of ggplots when exporting using officer R

北慕城南 提交于 2019-12-23 01:54:44

问题


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


回答1:


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




回答2:


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)



来源:https://stackoverflow.com/questions/49240961/how-to-increase-resolution-of-ggplots-when-exporting-using-officer-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!