如何在 R+Shiny 中禁用绘图点击

How to Disable Plot Clicking in R+Shiny

我有一个情节,我希望在点击按钮之前可以点击该情节。 shinyjs::disable 似乎无法解决问题。有没有办法做到这一点。

最小工作示例

library(shiny)

## ui.R
ui <- fluidPage(
    shinyjs::useShinyjs(),
    column(12,
    plotOutput("Locations", width=500, height=500,
        click="plot_click"), inline=TRUE ),
    actionButton("stop", "Stop")
)


## server.R
server <- function( input, output, session){

    x <- reactiveValues(x=runif(10))
    y <- reactiveValues(y=rnorm(10))

    ## Click To Generate New Random Points
    observeEvent(input$plot_click, {
        x$x <- runif(10)
        y$y <- rnorm(10)
    })

    ## Disable Clicking
    observeEvent(input$stop, {
        shinyjs::disable("plot_click")
    })    

    ## Render Plot
    output$Locations <- renderPlot({ 

        ## Constant
        par(bg=NA)

        plot.new()
        plot.window(
            xlim=c(0,1), ylim=c(0,1),
            yaxs="i", xaxs="i")
        axis(1)
        axis(2)
        grid(10,10, col="black")
        box()

        ## Updating
        points( x$x, y$y, cex=3, pch=16)

    })        
}

### Run Application
shinyApp(ui, server)

有几种方法可以做到这一点。 您可以阻止 server.R 中的逻辑触发新绘图的渲染:

选项 1.

## server.R
server <- function( input, output, session){

  x <- reactiveValues(x=runif(10))
  y <- reactiveValues(y=rnorm(10))

  disabled <- FALSE

  ## Click To Generate New Random Points
  observeEvent(input$plot_click, {
    if(disabled) return()
    x$x <- runif(10)
    y$y <- rnorm(10)
  })

  ## Disable Clicking
  observeEvent(input$stop, {
    disabled <<- TRUE
  })    

  ## Render Plot
  output$Locations <- renderPlot({ 
    # Create plot
  })        
}

选项 2。(jQuery)

或者您可以使用 jQuery 取消绑定点击事件:

## ui.R
ui <- fluidPage(
  tags$head(
    tags$script(
      HTML("
            Shiny.addCustomMessageHandler ('disablePlotClick',function (message) {
              $('#'+message.ID).unbind();
            });")
    )
  ),
  column(12,
         plotOutput("Locations", width=500, height=500,
                    click="plot_click"), inline=TRUE ),
  actionButton("stop", "Stop")
)

定义一个函数来调用Javascript函数:

disablePlotClick <- function(session, id){
  session$sendCustomMessage(type = 'disablePlotClick', message = c("ID"=id))
}

然后在您想要禁用点击事件时调用该函数即可:

## Disable Clicking
  observeEvent(input$stop, {
    disablePlotClick(session, 'Locations')
  })  

选项 2. (shinyjs)

这也可以使用 shinyjs 来完成:

jsCode <- "shinyjs.disablePlotClick = function(ID){ $('#'+ID).unbind(); console.log(ID);}"

## ui.R
ui <- fluidPage(
  shinyjs::useShinyjs(),
  shinyjs::extendShinyjs(text = jsCode, functions=c("disablePlotClick")),

  # More UI code
)

并调用函数:

## Disable Clicking
  observeEvent(input$stop, {
    js$disablePlotClick("Locations")
  })