Search code examples
rshinyr-plotly

R-Plotly: Box Select - Extract x & y Coordinates


For my project I need to extract the x and y coordinates of the “Box Select” which I use to select data within a shiny app (as I need to filter according to these values within a time frame). To be more precise - I need the actual coordinates only of the created box, not the x/y values of the selected IDs inside.

JS - Event Handlers <- I saw here that the event handler has these coordinates (x and y array) and you can see them in the console - but how do I store them dynamically within R?

Thanks already.

library(shiny)
library(plotly)

ui <- fluidPage(
   plotlyOutput('myPlot'),
   )

server <- function(input, output, session){
  output$myPlot = renderPlotly({
    plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length, color = ~Species) %>%
      layout(dragmode = "select")
  })
}

shinyApp(ui, server)

Solution

  • After trying around a lot I figured out that the data about the box range is not stored within the event_data of "selected", but they are available in both of "brushed" and "brushing".

    Here is my solution to get the range of the created box:

    library(shiny)
    library(plotly)
    
    ui <- fluidPage(
      plotlyOutput('myPlot'),
    )
    
    server <- function(input, output, session){
    
      output$myPlot = renderPlotly({
        plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length, color = ~Species, 
                type = 'scatter') %>%
          layout(dragmode = "select") %>%
          event_register(event = "plotly_brushed")
      })
    
      # Drag based selection in plotly graph
      selected_range <- reactiveVal({})
      observeEvent(event_data("plotly_brushed"), {
        # storing the values in a reactive value for later use
        selected_range(event_data("plotly_brushed"))
    
        # alternative method if you want to use it within the same observer/reactive  expression
        #xmin <- event_data("plotly_brushed")$x[1]
        #xmax <- event_data("plotly_brushed")$x[2]
        #ymin <- event_data("plotly_brushed")$y[1]
        #ymax <- event_data("plotly_brushed")$y[2]
      })
    }
    
    shinyApp(ui, server)