Skip to content

Instantly share code, notes, and snippets.

@PaulC91
Last active April 22, 2023 05:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PaulC91/c8d70008ab551380108e1b2707ce57ff to your computer and use it in GitHub Desktop.
Save PaulC91/c8d70008ab551380108e1b2707ce57ff to your computer and use it in GitHub Desktop.
Example of using shiny to allow a user to build several plots interactively and iteratively add them as slides of a ppt deck download
library(shiny)
library(magrittr)
library(ggplot2)
library(officer)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
sliderInput("obs", "Number of observations:", min = 10, max = 500, value = 100),
actionButton("add_plot", "Add to ppt"),
downloadButton("download", "Download PPT")
),
mainPanel(plotOutput("distPlot"))
)
)
server <- function(input, output) {
# reactive plot controlled by user inputs
current_plot <- reactive({
ggplot() + geom_histogram(aes(x = rnorm(input$obs)))
})
# render the current plot in shiny
output$distPlot <- renderPlot({
current_plot()
})
# create empty reactive list to store plots when user adds them
plot_list <- reactiveValues()
# when the add plot button is clicked, add the current plot to the reactive list
observeEvent(input$add_plot, {
plot_num <- paste0("plot_", input$add_plot)
plot_list[[plot_num]] <- current_plot() + labs(title = plot_num)
})
# when download button is clicked...
output$download <- downloadHandler(
filename = function() {
paste("ppt-download-", Sys.Date(), ".pptx", sep="")
},
content = function(file) {
# create a deck and add a title slide
mypres <- read_pptx() %>%
add_slide(layout="Title Slide", master="Office Theme") %>%
ph_with(value = "Hello world", location = ph_location_type(type = "ctrTitle")) %>%
ph_with(value = "Example of programmatically adding slides to deck with shiny", location = ph_location_type(type = "subTitle"))
# convert reactive plot list to normal list
plots <- reactiveValuesToList(plot_list)
# loop over each plot, adding it to a new slide in the deck
# the double arrow assignment allows for modifying an object outside of the
# environment the for loop is run in
for (i in seq_along(plots)) {
mypres <<- mypres %>%
add_slide(layout = "Title and Content", master = "Office Theme") %>%
ph_with(value = plots[[i]], location = ph_location_fullsize())
}
# download the deck
mypres %>%
print(target = file) %>%
invisible()
}
)
}
shinyApp(ui = ui, server = server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment