如何在 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)

有几种方法可以做到这一点。您可以阻止服务器中的逻辑。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 完成,如下所示:

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")
  }) 

最新更新