I would like to download PowerPoint slides from Shiny with the package officer. I made an PowerPoint example that contains a plot. How to update the slide if you change the inputs of the plot? Because when I changed the inputs, it didn't update the plot but it added a new slide with the modified plot. That's not what I want. I want to update the plot based on the inputs. How to achieve that? Here is a reproducible example:
- Import libraries and define useful functions
# Import packages ---------------------------------------------------------
library(shiny)
library(tidyr)
library(dplyr)
library(ggplot2)
library(officer)
# Useful functions --------------------------------------------------------
IsNumeric <- function(x){return(is.numeric(x) == TRUE)}
IsNotNumeric <- function(x){return(is.numeric(x) == FALSE)}
- Define the user interface
# Define user interface ---------------------------------------------------
ui <- fluidPage(
titlePanel("Dataset analysis"),
sidebarLayout(
sidebarPanel(
# Select categorical variables:
selectInput(inputId = "CatVar"
, label = "Select categorical variables:"
, choices = diamonds %>% select_if(IsNotNumeric) %>% colnames()
, multiple = TRUE
),
selectInput(inputId = "NumVar"
, label = "Select categorical variables:"
, choices = diamonds %>% select_if(IsNumeric) %>% colnames()
, multiple = FALSE
)
),
mainPanel(
plotOutput(outputId = "plot_id"),
downloadButton(outputId = "pptx_id"
, label = "Download analysis to PowerPoint"
)
)
)
)
- Define the server function
mypptx <- read_pptx()
server <- function(session, input, output){
selectCatVar <- reactive({
validate(
need(is.null(input$CatVar) == FALSE, "Please select at least one categorical variable.")
)
input$CatVar
})
# selectNumVar <- reactive({input$NumVar})
myplot <- reactive({
dat <- diamonds %>% select(selectCatVar(), input$NumVar) %>%
gather(MyVar, MyValue, -input$NumVar)
ggplot(data = dat, mapping = aes(x = MyValue, y = !!sym(input$NumVar), fill = MyValue)) +
geom_boxplot() +
facet_wrap(MyVar ~ ., scales = "free_x") +
labs(y = input$NumVar) +
theme(legend.position = "none"
)
})
output$plot_id <- renderPlot({
myplot()
})
output$pptx_id <- downloadHandler(
filename = function(){"test_pptx.pptx"},
content = function(file){
mypptx %>% add_slide(layout = "Title and Content", master = "Office Theme") %>%
ph_with(value = myplot(), location = ph_location_type(type = "body")) %>%
print(target = file)
}
)
}
- Run the application
shinyApp(ui = ui, server = server)