Skip to content

Instantly share code, notes, and snippets.

@shannonpileggi
Created October 18, 2024 12:33
Show Gist options
  • Save shannonpileggi/e4972f6e2cbc8b09f593ba920fad3cf8 to your computer and use it in GitHub Desktop.
Save shannonpileggi/e4972f6e2cbc8b09f593ba920fad3cf8 to your computer and use it in GitHub Desktop.
Create a power point slide deck from ggplot objects in R
#' Convert ggplot object to dml object to create editable powerpoint slides
#'
#' @param plot ggplot object or list of ggplot objects
#'
#' @return a dml object from the ggplot
#' @export
create_dml <- function(plot){
rvg::dml(ggobj = plot)
}
#' Create a power point slide deck from ggplot objects
#'
#' @param plot ggplot object or list of ggplot objects
#' @param path file path for where the power point should be saved
#' @param left left margin (in) of power point
#' @param top top margin (in)
#' @param width width (in) of exported figure
#' @param height height (in) of exported figure
#' @param editable whether to convert to an editable figure in powerpoint (TRUE), or export as an image to powerpoint (FALSE)
#'
#' @return a power point slide deck with 1 slide per figure
#' @export
#'
#' @examplesIf FALSE
#' f1 <- ggplot(mpg, aes(displ, hwy, colour = class)) + geom_point()
#' f2 <- ggplot(mpg, aes(displ, hwy, colour = class)) + geom_line()
#' figures <- list(f1, f2)
#' create_pptx(f1, "f1.pptx") # single plot
#' create_pptx(figures, "figures.pptx") # multiple plots
create_pptx <- function(plot, path, left = 0.5, top = 1, width = 9, height = 4.95, editable = TRUE){
rlang::check_installed("officer")
# create new PowerPoint ----
out <- officer::read_pptx()
# check to see if it is a single ggplot, if so convert to list
class_plot <- class(plot)
if(class_plot[1] == "gg") plot <- list(plot)
# for editable, convert to rvb ----
if (editable == TRUE) plot <- purrr::map(plot, create_dml)
all_slides <- purrr::map(
plot,
.f = ~ out %>%
officer::add_slide() %>%
officer::ph_with(.x, location = officer::ph_location(
width = width, height = height, left = left, top = top))
)
all_slides %>% base::print(target = path)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment