In the plan, how to save information about choosing a lasso and a pressed point?

I use plotly::ggplotly(), and I need the user to be able to select one point and select multiple points with a brush. I want both choices to exist in parallel. The user should be able to click on a point, and the lasso should select several points, and both of these pieces of information should be recorded.

The problem that I am facing is that if I click on a point, then the lasso selection will be reset. But the opposite is not true: if I select a lasso and then click on a point, then both are saved.

Here is the gif of this problem

Here is my code:

library(shiny)
library(plotly)

ui <- fluidPage(
  plotlyOutput("plot"),
  verbatimTextOutput("click"),
  verbatimTextOutput("brush")
)

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)

Playback:

  • Click one point
  • Make a Lasso Choice
  • Both are currently visible.
  • Select another point.
  • Now information on choosing a lasso is missing
  • , .
+4
1

event_data renderPrint(), . /, , :

ui <- fluidPage(
    plotlyOutput("plot"),
    verbatimTextOutput("click"),
    verbatimTextOutput("brush")
)

server <- function(input, output, session) {
    frame1 <- data.frame()
    frame2 <- data.frame()
    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)) {
            frame1 <<- frame1[is.null(frame1$pointNumber), ] # Optional line to remove the previous selections
            frame1 <<- rbind(frame1, d) 
        }
            frame1
        })

    output$brush <- renderPrint({
        d <- event_data("plotly_selected")
        if (!is.null(d)) {
            frame2 <<- frame2[is.null(frame2$pointNumber), ] # Optional line to remove the previous selections 
            frame2 <<- rbind(frame2, d)
        }
            frame2

    })

}

shinyApp(ui, server)
+1

Source: https://habr.com/ru/post/1685982/


All Articles