Ggplot2: how to distinguish a click from a brush?

I want my shiny application to have a plot that the user can click or select certain areas, so I use the click and brush plotOutput . My problem is that when the brush starts, the click handler is also called. I want to know when a click is made, and I want to know when a brush is made, but if the click is part of the brush, I want to ignore it.

Example: in the following application, if you just click (click somewhere and drag the mouse), you will receive a β€œclick” message, as well as a β€œbrush” message. I only want to get the message "brush" in this case.

 library(shiny) library(ggplot2) runApp(shinyApp( ui = fluidPage( plotOutput("plot", click = "click", brush = "brush") ), server = function(input, output, session) { output$plot <- renderPlot({ ggplot(mtcars, aes(wt, mpg)) + geom_point() }) observeEvent(input$click, { cat("clicked\n") }) observeEvent(input$brush, { cat("brushed\n") }) } )) 
+8
r shiny ggplot2
source share
1 answer

I know that this is just a workaround, but the only solution to this was to undo the last click when the brush was activated; I needed this for a plot where the user could add points by clicking. Using a brush will first create a point and delete it after releasing the click button. Just a flaw: sometimes you click and make a micro-brush without noticing, in this case it will not create a point explicitly. My application:

 library(shiny); library(dplyr); library(ggplot2) ui <- fluidPage( fluidRow( h1("add by clicking anywhere on the plot"), plotOutput("mainplot", click="mainplot_click", brush=brushOpts(id="mainplot_brush")) ), fluidRow( actionButton("add", "add"), actionButton("reset", "reset") ) ) server <- function(input, output, session) { vals = reactiveValues( keeprows = rep(TRUE, nrow(mtcars)), mydata = mtcars ) observeEvent(input$mainplot_click, handlerExpr = { my.x = input$mainplot_click$x my.y = input$mainplot_click$y vals$mydata <- vals$mydata %>% bind_rows(data.frame("wt"=my.x, "mpg"=my.y)) }) output$mainplot = renderPlot({ temp = vals$mydata ggplot() +geom_point(data=temp, col="black", fill="white", size=3) + aes(x=wt, y=mpg) }) observeEvent(input$mainplot_brush, handlerExpr = { vals$mydata <- vals$mydata %>% head(-1) }) observeEvent(input$reset, handlerExpr = { vals$mydata <- mtcars vals$keeprows <- rep(TRUE, nrow(mtcars)) }) session$onSessionEnded(stopApp) } shinyApp(ui, server) 
0
source share

All Articles