-
Notifications
You must be signed in to change notification settings - Fork 2
Open
Description
Below is a minimal reproducible toy shiny app where the number of plot outputs is dependent on a user input (the slider). The get_code() function was able to capture the dynamic UI on the server side (output$plots) but not the actual plot outputs (output[[plotname]]) in the for() loop.
library(shiny)
library(scriptgloss)
ui<-function(request){
fluidPage(sidebarLayout(
sidebarPanel(
sliderInput("n", "Number of plots", value=1, min=1, max=5)),
mainPanel(
uiOutput("plots"))
),
verbatimTextOutput("code")
)
}
server<-function(input, output, session){
##################### dynamic number of outputs ######################
## code based on the solution to this question:
## https://stackoverflow.com/questions/31686773/shiny-dynamic-number-of-output-elements-plots
max_plots <- 5
# Insert the right number of plot output objects into the web page
output$plots <- renderUI({
plot_output_list <- lapply(1:input$n, function(i) {
plotname <- paste("p", i, sep="")
plotOutput(plotname, height = 280, width = 250)
})
# Convert the list to a tagList - this is necessary for the list of items
# to display properly.
do.call(tagList, plot_output_list)
})
# Call renderPlot for each one. Plots are only actually generated when they
# are visible on the web page.
for (i in 1:max_plots) {
# Need local so that each item gets its own number. Without it, the value
# of i in the renderPlot() will be the same across all instances, because
# of when the expression is evaluated.
local({
my_i <- i
plotname <- paste("p", my_i, sep="")
output[[plotname]] <- renderPlot({
plot(1:my_i, 1:my_i,
xlim = c(1, max_plots),
ylim = c(1, max_plots),
main = paste("1:", my_i, ". n is ", input$n, sep = "")
)
})
})
}
################ get code #################
output$code <- renderText({
get_code(server)
})
}
shinyApp(ui=ui, server=server)
Metadata
Metadata
Assignees
Labels
No labels