How to detect brushed bins in geom_histogram with brushedPoints?

Hi there,

first post in here, so apologies if I fail certain forum rules.

I'd like to detect the bin selection in a ggplot histogram using a horizontal brush event. This is my (simplified) program:

library(shiny)
library(ggplot2)
library(dplyrr)

ui = fluidPage(
    plotOutput("iris_hist", click = "plot_click", brush = brushOpts("plot_brush", resetOnNew = T, direction = "x"))
)

server = function(input, output, session) {

    observeEvent(input$plot_brush, {
        selectedRange = brushedPoints(streamData(), iris)
        ## errors !!!
    })

    output$iris_hist = renderPlot({
             iris %>% ggplot(aes(Sepal.Width)) + geom_histogram()
    })
}

shinyApp(ui, server)

It starts fine, but after selecting a range in the histogram it fails with the following error

Warning: Error in brushedPoints: brushedPoints requires a brush object with xmin, xmax, ymin, and ymax.
  74: stop
  73: brushedPoints
  72: observeEventHandler [d:/documents/arbeitsmappe/snippets/R/shiny/realttime_dashhboard/scratches/brushOptsHist.R#12]
   1: shiny::runApp

What am I doing wrong? Is there an alternative to brushPoints for ggplot histograms, or could I instrument it differently to provide the selected bins?

Best regards,
Holger

I notice that your code as provided has a small typo dplyrr rather than dplyr
more importantly perhaps, there's a mystery streamData() object

Indeed, thanks for the pointer. I think, I was using it incorrectly. Here's the corrected example cdoe which works great

library(shiny)
library(ggplot2)
library(dplyr)

ui = fluidPage(
plotOutput("iris_hist", click = "plot_click", brush = brushOpts("plot_brush", resetOnNew = T, direction = "x"))
)

server = function(input, output, session) {

    observeEvent(input$plot_brush, {
        # browser()
        selectedRange = brushedPoints(iris, input$plot_brush)
        # print(selectedRange)
        print(summarize(selectedRange, num_points=n(), range(Sepal.Width)))
    })

    output$iris_hist = renderPlot({
        iris %>% ggplot(aes(Sepal.Width)) + geom_histogram()
    })
}

shinyApp(ui, server)

There is just one minor flaw: Occasionally the server receives a brush event although the mouse has not been released yet. Is there any way to avoid that? In plotly there is the distinction between selecting and selected (see https://plotly.com/javascript/plotlyjs-events/#event-data), I wonder if shiny supports a similar concept? Or is this just a (known) bug?

Thanks,
Holger

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.