Mouse click event in rshiny

3.4k views Asked by At

I'm trying to use click events using the plot_click option in RShiny. What I want to do is:I want to select a particular bubble from the first chart and then the chart below should be populated only for the above selected car. How to do this? Here is my code :

ui <- basicPage(
  plotOutput("plot1", click = "plot_click"),
  plotOutput("plot2")  
)

server <- function(input, output) {
  output$plot1 <- renderPlot({
    plot(mt$wt, mt$mpg)
  })

  output$plot2 <- renderPlot({
    test <- data.frame(nearPoints(mt, input$plot_click, xvar = "wt", yvar = "mpg"))
    test2 <- filter(test,Car_name)
    car <- test2[1,1]
    mt2 <- filter(mt,Car_name == car)
    plot(mt2$wt,mt2$mpg)

  })
}
shinyApp(ui, server)
1

There are 1 answers

0
SeGa On

I rearranged your server-function a bit. I moved the selected points to a reactive Value, which can be used by print/plot outputs. Furthermore, i am not exactly sure what you want to achievewith all that filtering. Maybe you could change your original question an make a reproducible example out of it with the mtcars-data, as it seems you are using that.

library(shiny)
ui <- basicPage(
  plotOutput("plot1", click = "plot_click"),
  verbatimTextOutput("info"),
  plotOutput("plot2")
)

server <- function(input, output) {
  output$plot1 <- renderPlot({
    plot(mtcars$wt, mtcars$mpg)
  })

  selected_points <- reactiveValues(pts = NULL)
  observeEvent(input$plot_click, {
    x <- nearPoints(mtcars, input$plot_click, xvar = "wt", yvar = "mpg")
    selected_points$pts <- x
  })

  output$info <- renderPrint({
    selected_points$pts
  })

  output$plot2 <- renderPlot({
    req(input$plot_click)
    test <- selected_points$pts
    plot(test$wt,test$mpg)
  })
}
shinyApp(ui, server)

The clicked points are stored in the selected_points reactive Value, which is assigned in the observeEvent function. If you filter a lot in the plot2-function, you would have to use req() or validate(), as it may be possible that no value is left over and therefore nothing can be plotted.

I hope that helps.