R Shiny loop to display multiple plots

前端 未结 1 1248
误落风尘
误落风尘 2020-12-06 09:10

Ok I have code that you can run below. I am trying to modify this code:

https://gist.github.com/wch/5436415/

so that max_plots is dynamically set using input

相关标签:
1条回答
  • 2020-12-06 09:25

    So max_plots is hard coded. When you launch the app, the loop for (i in 1:max_plots ) { (It runs only once) creates 5 (= max_plots) new output elements (output$plot1 output$plot2 ...) which render a plot, but the plots are displayed only when the respectiveplotOutputsexists in the UI. TheplotOutputs are created dynamically in the functionlapply(1:input$n, function(i) {input$n is the value of the slider. 5 plots are created but we only createinput$nplot outputs. That's why this is dynamic even ifmax_plots` is hard coded.

    If you want you can replace max_plots by the dynamic parameter but you need to include the loop into and observer. And it will run each time input$n changed.

    For example :

    observe({
        for (i in 1:input$n) {
            # 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("plot", 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 = "")
                )
              })
            })
         }
    })
    

    I don't know what your function returns but i suppose it can also work if you include it into the server function and inside a reactive function in which you can read input object.

    observe({ 
        max_plots<-length(getTerm1UI(input$Desk, input$Product, input$File1))
        for(i in 1:max_plots) {
           ...
    
    0 讨论(0)
提交回复
热议问题