Black Lives Matter. Please consider donating to Black Girls Code today.

How do I retain the information about both the lasso selection and the clicked point?

I’m using plotly::ggplotly() and I need the user to be able to both select a single point and to select multiple points with brushing. I want both selection options to exist in parallel. The user should be able to click on a point and to lasso select several points, and both of those pieces of information should be recorded.

The problem I’m having is that if I click on a point, then the lasso selection gets reset. But the opposite is not true: if I lasso select and then click on a point, then both are retained.

Here’s a GIF of this issue

Here’s my code:


ui <- fluidPage(

server <- function(input, output, session) {
  nms <- row.names(mtcars)
  output$plot <- renderPlotly({
    p <- ggplot(mtcars, aes(x = mpg, y = wt, key = nms)) + geom_point()
    ggplotly(p) %>% layout(dragmode = "lasso")
  output$click <- renderPrint({
    d <- event_data("plotly_click")
    if (!is.null(d)) d
  output$brush <- renderPrint({
    d <- event_data("plotly_selected")
    if (!is.null(d)) d

shinyApp(ui, server)

To reproduce:

  • Click a single point
  • Do a lasso selection
  • Both are currently visible
  • Click a different point
  • Now the lasso selection information is gone
  • Do a lasso selection again, both are visible again

@daattali Thanks for the clean example and GIF. A more expressive API for selecting data is being developed in the plotly.js repo, you can follow the progress here:

@daattali did you by now perhaps discover a way to save a lasso definition as R variable or function? I’ve just came across this post when looking into whether that is even possible or not

No I did not. I had to modify my requirements and not support it

That is a shame. Did you try to talk with cievert about this directly?
Looks like a very useful tool to me for isolating the same selection region across plots of different files / data sets that are plotted

I can’t recall if I spoke to him at the time. I might have. It also might be fixed by now, I haven’t tried. @carson might know better

It’s not fixed, and I don’t view it as a high priority problem since you can ‘retain’ selection data via shiny::reactiveValues()

I could imagine a nice solution like storing a selection region and going through a list of files (data frames) to count the abundance of points in that region, or even multiple region. That way plotly could be used to build manual clustering tools in R shiny.

Hi Daattali,

Have you solved the problem? I have save issue as you. If yes, can you please post the your solution.

Thank you very much for your help and time in advance!