Search code examples
rplotlyhistograminteractivecrosstalk

Crosstalk interactive slider not working with histogram


I want to create an interactive histogram in R using crosstalk. Specifically, I want to use a slider to select what data appears on a histogram. To do so, I used the following code:

shared_data <- highlight_key(mpg)

widgets <- bscols(
  widths = 12,
  filter_slider("displ", "displ", shared_data, ~displ))

bscols(widths = 10, widgets, 
  plot_ly(x = ~mpg$displ, type = "histogram",
          histnorm = "probability"))

This creates a histogram as well as an interactive slider. However, the slider doesn't actually do anything.

I've tried an alternate piece of code to do this, but similarly to the previous code, it creates the histogram and a slider which fails to filter the data.

shared_data <- mpg %>%
  SharedData$new()

plot_ref <- plot_ly(x = ~mpg$displ, type = "histogram",
                    histnorm = "probability") %>%
  layout(title = "Reference Histogram (Displ)",
         xaxis = list(title = "Displ"),
         yaxis = list(title = "Percentage (%)"))

bscols(widths = 10,
       list(filter_slider(id = "slider_ap", label = "Displ",
                          sharedData = shared_data, column = ~displ),
            plot_ref))

Can anyone explain what is wrong with the code above? I read somewhere that crosstalk interactivity isn't specifically optimized for histograms, could this be the reason it doesn't work? Any help is greatly appreciated!


Solution

  • The purpose of SharedData is to share the data. When you called the plot, you didn't use the shared data, so the filter had no way of matching the plot.

    Check it out:

    shared_data <- mpg %>%
      SharedData$new()
    
    plot_ref <- plot_ly(data = shared_data, # <- share it
                        x = ~displ, type = "histogram",
                        histnorm = "probability") %>%
      layout(title = "Reference Histogram (Displ)",
             xaxis = list(title = "Displ"),
             yaxis = list(title = "Percentage (%)"))
    
    bscols(widths = 10,
           list(filter_slider(id = "slider_ap", label = "Displ",
                              sharedData = shared_data, column = ~displ),
                plot_ref))
    

    enter image description hereenter image description here

    enter image description hereenter image description here