library(shiny)
library(plotly)
library(tidyverse) # includes purrr::map*
library(rlang) # for list2()
ui <- fluidPage(
actionButton("btn","add a plot"),
uiOutput("myui")
)
server <- function(input, output, session) {
my_plots <- reactiveVal(NULL)
observeEvent(input$btn,{
existing <- my_plots()
new_plot_name <- paste0("plot",input$btn)
new_plot <- plot_ly(economics,x=~date,
y=as.formula(paste0("~",sample(c("pce" , "pop" ,"psavert", "uempmed" ,"unemploy"),
1))),
type="scatter",mode="markers") %>% layout(title=new_plot_name)
new_named_plot <- list2(!!sym(new_plot_name) := new_plot)
new_plot_list <- append(existing,new_named_plot)
my_plots(new_plot_list)
output[[new_plot_name]] <- renderPlotly({
new_plot
})
})
output$myui <- renderUI({
mp <- req(my_plots())
imap(mp,
~{plotlyOutput(.y)})
})
}
shinyApp(ui, server)