简体   繁体   中英

Challenge with dynamically generated, interactive R Shiny plots (mostly functioning code)

Below is the minimum code. It works, but there is a weird problem. Here is what works:

  1. User can select a number of plots (default is 3).
  2. User can click in a plot and have that value represented (partly works).

Steps to reproduce the "partly works":

  1. At launch, click in plot #3, no problem.
  2. Click in plot #2, nothing happens.
  3. Reduce the number of plots from 3 to 2 and then back to 3.
  4. Click in plot #2, now it works.
  5. Click in plot #1, nothing happens.
  6. Reduce the number of plots from 3 to 1 and then back to 3.
  7. Click in plot #1, now it works.

If you reload the app, and start with step 6 above, all plots are interactive as expected.

rm(list=ls())
library(shiny)

#
# Dynamic number of plots: https://stackoverflow.com/questions/26931173/shiny-r-renderplots-on-the-fly
# That can invalidate each other: https://stackoverflow.com/questions/33382525/how-to-invalidate-reactive-observer-using-code
#

ui <- (fluidPage(sidebarLayout(
         sidebarPanel(
            numericInput("np", "Plots:", min=0, max=10, value=3, step=1)
         )
         ,mainPanel(
            fluidRow(uiOutput("plots"))
         )
)))

server <- function(input, output, session) {
   val <- reactiveValues()
   dum <- reactiveValues(v=0)
   obs <- list()

    ### This is the function to break the whole data into different blocks for each page
    plotInput <- reactive({
      print("Reactive")
      np <- input$np
      for(i in 1:np) {
         cx <- paste0("clk_p",i); dx <- paste0("dbl_p",i); px <- paste0("p",i)
         obs[[cx]] <- observeEvent(input[[cx]], {
            req(input[[cx]]); val[[px]] <- input[[cx]]$x; dum$v <- dum$v+1; print(paste("Dum",dum$v))
         })
         obs[[dx]] <- observeEvent(input[[dx]], {
            req(input[[dx]]); val[[px]] <- NULL
         })
      }

      return (list(np=np))
    })

    ##### Create divs######
    output$plots <- renderUI({
      print("Tag plots")
      pls <- list()
      for(i in 1:plotInput()$np) {
         pls[[i]] <- column(4,
                           plotOutput(paste0("p",i), height=200, width=200
                                     ,click=paste0("clk_p",i)
                                     ,dblclick=paste0("dbl_p",i))
                         )
      }
      tagList(pls)
    })

    observe({
      print("Observe")
      lapply(1:plotInput()$np, function(i){
        output[[paste("p", i, sep="") ]] <- renderPlot({
          print(paste("Plot",dum$v))
          x <- val[[paste0("p",i)]]
          x <- ifelse(is.null(x),"NA",round(x,2))
          par(mar=c(2,2,2,2))
          plot(x=runif(20), y=runif(20), main=i, xlim=c(0,1), ylim=c(0,1), pch=21, bg="gray", cex=1.5)
          if(is.numeric(x)) abline(v=x, col="blue")
          rm(x)
        })
      })
    })
}

shinyApp(ui, server)

Here is a working version of what you're trying to do:

library(shiny)

ui <- fluidPage(
  sidebarPanel(
    numericInput("num", "Plots:", 3)
  ),
  mainPanel(
    uiOutput("plots")
  )
)

server <- function(input, output, session) {
  obs <- list()
  val <- reactiveValues()

  observe({
    lapply(seq(input$num), function(i){
      output[[paste0("plot", i) ]] <- renderPlot({
        click_id <- paste0("clk_p",i);
        plot(x = runif(20), y = runif(20), main=i)
        if (!is.null(val[[click_id]])) {
          abline(v = val[[click_id]], col = "blue")
        }
      })
    })
  })
  observe({
    lapply(seq(input$num), function(i){
      id <- paste0("clk_p",i);
      if (!is.null(obs[[id]])) {
        obs[[id]]$destroy()
      }
      val[[id]] <- NULL
      obs[[id]] <<- observeEvent(input[[id]], {
        cat('clicked ', id, ' ', input[[id]]$x, '\n')
        val[[id]] <- input[[id]]$x
      }, ignoreInit = TRUE)
    })
  })

  output$plots <- renderUI({
    lapply(seq(input$num), function(i) {
      id <- paste0("plot", i)
      plotOutput(id, height=200, width=200, click=paste0("clk_p",i))
    })
  })
}

shinyApp(ui,server)

A few main pointers for anyone who sees this in the future:

  • The main issue with the original code was that all the observers were registering only for the last ID. This is a bit of an advanced concept and has to do with the way environments in R work and because they were created in a for loop. The fix for this is to use lapply() instead of a for loop to create the observers
  • Another issue is that obs was overwriting the observers in the list, but the previous observers still exist and can still fire, so I added logic to destroy() existing observers.
  • One of the most important rules in shiny is to not place side effects inside reactives ( plotInput has side effects) so I rewrote the code in a way that avoids that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM