Save Plots in Different Formats

Table of Contents

Introduction

This notebook covers extracting plots in different formats.

Code

library(officer)
library(rvg)

.esp, .pdf, .png, .tiff formats.

postscript("Figure1-RHPD-ForestPlot-v20210729.eps", width=13, height=14, pointsize=12)
pdf("ForestPlot.pdf", width=11, height=8, pointsize=16)
png("ForestPlot.png", width=11, height=8, units = 'in', pointsize=16, res = 300)
tiff("Figure1-RHPD-ForestPlot-v20210729.tiff", res=800, width=13, height=9, units="in", pointsize=14, compression="none")

dev.off()

Extract any type of plot into a .pptx file, one plot each file

topptx(figure = a,file="plots.pptx", width=6, height=5,append=T)

Extract a list of ggplot into .pptx

create_pptx <- function(plot, path, left = 0.5, top = 1, width = 7, height = 6){
  
    # if file does not yet exist, create new PowerPoint ----
    if (!file.exists(path)) {
        out <- officer::read_pptx()
    }
    # if file exist, append slides to exisiting file ----
    else {
        out <- officer::read_pptx(path)
    }
  
    out %>% 
      officer::add_slide() %>% 
      officer::ph_with(plot, location = officer::ph_location(
        width = width, height = height, left = left, top = top)) %>% 
      base::print(target = path)
}

create_dml <- function(plot){
  rvg::dml(ggobj = plot)
}
diamonds_dml <- purrr::map(list(a,b,c,d), create_dml)

purrr::map(
  # dml plots to export ----
  diamonds_dml, 
  # exporting function ----
  create_pptx, 
  # additional fixed arguments in create_pptx ----
  path = here::here(
    "demo_many.pptx"
    )
  )

Session Info

sessionInfo()
## R version 4.4.0 (2024-04-24 ucrt)
## Platform: x86_64-w64-mingw32/x64
## Running under: Windows 11 x64 (build 22000)
## 
## Matrix products: default
## 
## 
## locale:
## [1] LC_COLLATE=English_United States.utf8 
## [2] LC_CTYPE=English_United States.utf8   
## [3] LC_MONETARY=English_United States.utf8
## [4] LC_NUMERIC=C                          
## [5] LC_TIME=English_United States.utf8    
## 
## time zone: America/New_York
## tzcode source: internal
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## loaded via a namespace (and not attached):
##  [1] digest_0.6.33     R6_2.5.1          bookdown_0.35     fastmap_1.1.1    
##  [5] xfun_0.43         blogdown_1.18     cachem_1.0.8      knitr_1.46       
##  [9] htmltools_0.5.4   rmarkdown_2.25    cli_3.6.1         sass_0.4.5       
## [13] jquerylib_0.1.4   compiler_4.4.0    rstudioapi_0.15.0 tools_4.4.0      
## [17] evaluate_0.22     bslib_0.5.1       yaml_2.3.6        jsonlite_1.8.7   
## [21] rlang_1.1.1
Oncology QS
Oncology QS
The Nerd of Biostat&Bioinfo

Our research interest include biostatistics and bioinformatics.