#' @title Save graph objects
#'
#' @description Export high-quality, scalable graphics for both print and online.
#'
#' @param graph Either a DiagrammeR graph object or a diagram generated by \code{render_graph()}.
#' @param filename String for filename. Defaults to \code{NULL}.
#' @param filetype One of \code{pdf}, \code{eps}, \code{pdf}, \code{svg}. Defaults to \code{pdf}.
#' @param embed Defaults to FALSE. Automatically set to TRUE by \code{qd_embed()}.
#' @param ... Pass arguments to \code{render_graph()}, e.g., width and height (pixels) for .png files.
#'
#' @describeIn qd_save
#'
#' @import rsvg
#' @import DiagrammeRsvg
#' @export qd_save
qd_save <- function(graph, filename = NULL, filetype = "pdf", embed = F, ...) {
# File Format Match Table -----------------------------------------------
fmt.opts <- c("png" = "rsvg_png",
"eps" = "rsvg_ps",
"pdf" = "rsvg_pdf",
"svg" = "rsvg_svg")
# Checks ----------------------------------------------------------------
## check for valid filetype
if (!filetype %in% names(fmt.opts)) {
stop(paste("Filetype not supported. Choose one of:",
paste0(names(fmt.opts), collapse = ", ")))
}
## check for filename
if (is.null(filename)) {
stop("Must specify the 'filename' option.")
}
# Graph Object ----------------------------------------------------------
## detect whether 'graph' = graph object or pre-rendered graph
if (class(graph)[1] == "dgr_graph") {
rendered.graph <- render_graph(graph, ...)
} else if (class(graph)[1] == "grViz") {
rendered.graph <- graph
}
# File Save -------------------------------------------------------------
file.fmt <- match.arg(filetype, names(fmt.opts))
raw.img <- charToRaw(export_svg(rendered.graph))
## generate filename/path and make visible to qd_embd()
fname <- paste(filename, file.fmt, sep = ".")
if (embed) assign("fname", fname, envir = parent.frame())
## matches and calls rsvg_pdf(), rsvg_ps(), rsvg_eps(), or rsvg_svg
out <- do.call(fmt.opts[[file.fmt]], list(raw.img, file = fname))
return(out)
}
#' @title Embed diagrams in RMarkdown
#' @description A wrapper around \code{qd_save()} meant for use within R code chunks in RMarkdown documents.
#'
#' @param ... Pass arguments to \code{qd_save()}.
#'
#' @export qd_embed
qd_embed <- function(...) {
qd_save(..., embed = T)
knitr::include_graphics(fname) # fname from qdsave()
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.