show with app
library(shiny)
library(plotly)

ui <- fluidPage(
  radioButtons("plotType", "Plot Type:", choices = c("plotly")),
  plotlyOutput("plot"),
  #verbatimTextOutput("hover"),
  verbatimTextOutput("click"),
  verbatimTextOutput("probs")
  #verbatimTextOutput("selecting"),
  #verbatimTextOutput("brushed"),
  #verbatimTextOutput("selected")
)

server <- function(input, output, session) {

  nms <- row.names(mtcars)

  tidx <- reactiveVal(NA_integer_)

  output$plot <- renderPlotly({
    p <- if (identical(input$plotType, "ggplotly")) {
      ggplotly(ggplot(mtcars, aes(x = mpg, y = wt, customdata = nms)) + geom_point())
    } else {
      x <- 0:8
      cols <- rep("blue", length(x))
      colidx <- tidx() + 1
      cols[colidx] <- "red"
      plot_ly(x = x, y = dbinom(x, max(x), 0.5), type = 'bar',
              marker = list(color = cols), source = "A") # <- source pairs with event_data to mark correct plot
    }
    p %>%
      layout(dragmode = "select") %>%
      event_register("plotly_selecting")
  })


  output$click <- renderPrint({
    d <- event_data("plotly_click")
    print(d)
    print(class(d))
    nn <- d$x
    pos_idx <- isolate(tidx())
    if (length(nn) != 0) {
      if (nn %in% pos_idx) {
        idx <- which(nn == pos_idx)
        newidx <- pos_idx[-idx]
      } else {
        newidx <- c(nn, pos_idx)
      }
      newidx <- sort(newidx)
      tidx(newidx)
    }
    print(tidx())
    if (is.null(d)) "Click events appear here (double-click to clear)" else d
  })

  output$probs <- renderPrint({
    x <- 0:8
    colidx <- tidx() + 1
    pp <- dbinom(x, max(x), 0.5)
    ppp <- sum(pp[colidx])
    paste0("Probability: ", round(ppp, 4))
  })


}

shinyApp(ui, server, options = list(display.mode = "showcase"))