#' Save multiple plots in one PDF.
#'
#' Convenient function for saving multiple plots stored in a list. The function
#' can also add bookmarks to the created pdf files.
#'
#' @param .data a tbl.
#' @param ... one or more list-columns where plots are stored.
#' @param files character vector. One file path for each column.
#' @param width width of the plots.
#' @param height height of the plots.
#' @param bookmarks Bookmarks to be added to the PDF. A list of columns generated by vars().
#' Columns will be interpreted as hierarchical groups and order matters.
#' Plots will be reodered according to bookmarks in the PDF.
#' If \code{NULL} (default), no bookmarks are added to the PDF.
#' @param gs.exec a path to your Ghostscript executable
#' (necessary to add bookmarks).
#'
#' @details
#' Bookmarks are added to pdf using Ghostscript, a third party program which
#' must be installed manually by the user. Tested on Linux only, probably not working
#' on Windows.
#'
#'
#'
#' @export
#'
save_plots <- function(.data, ...,
files, width = 8, height = 6,
bookmarks = NULL, gs.exec = "gs"){
.data <- dplyr::arrange(.data, !!!bookmarks)
plot_cols <- dplyr::select(.data, ...)
if(!is.null(bookmarks)){
bk_dat <- dplyr::select(.data, !!!bookmarks)
bk_dat <- as.matrix(bk_dat)
res <- flat_fac(bk_dat)
bk_file <- tempfile(fileext = ".info")
writeLines(res, bk_file)
}
map2(plot_cols, files, function(plot_col, file){
pdf(file, width = width, height = height)
invisible(lapply(plot_col, print))
dev.off()
if(!is.null(bookmarks)){
bridge_file <- tempfile(fileext = ".pdf")
comm_gs <- paste0(gs.exec, " -sDEVICE=pdfwrite -q -dBATCH -dNOPAUSE ",
"-sOutputFile=", bridge_file,
" -dPDFSETTINGS=/prepress ", bk_file,
" -f ", file,
" && mv ", bridge_file, " ", file)
system(comm_gs)
}
})
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.