Selecting a default value in an R plotly plot using a selectize box via crosstalk in R, using static html not shiny

In an Rmarkdown html document, how does one select a default value for a crosstalk::filter_select dropdown that will work with plotly plots? E.g., in the example below, to have just group ‘a’ selected when the RMD is knitted.

I know that for the reprex below example using plotly buttons would be easier, but when there are more than 4-5 or so choices the plotly dropdowns/buttons take up too much room/are quite ugly. Also hoping to avoid running a shiny server, the idea is to have everything running client side for speed purposes.

There is a PR in crosstalk that adds a "default choice" argument to the filter_select function, but that version doesn’t work with plotly ( I would guess the easiest way would be to add javascript to the doc to manipulate the crosstalk object, but a few experiments haven’t gotten very far yet.

Reprex rmd:


```{r echo=FALSE, message=FALSE, warning=FALSE}

# example data 
dat <- tibble::tribble(~filterBy, ~x, ~y,
                        "a", 1, 1,
                        "b", 2, 1,
                        "a", 1, 2,
                        "b", 2, 2,
                        "a", 1, 3,
                        "b", 2, 3,
                        "a", 1, 2,
                        "b", 2, 3,
                        "c", 3, 1,
                        "c", 3, 2,
                        "c", 3, 3

# initializing a crosstalk shared data object  
plotdat <- highlight_key(dat)

# Filter dropdown
question_filter <- crosstalk::filter_select(
   "filter", "Select a group to examine",
   plotdat, ~filterBy, multiple = F

# Plotting:
plot <-  plot_ly( plotdat, 
    x = ~x, y = ~y, text = ~filterBy,  mode = "markers+text", 
    textposition = "top", hoverinfo = "x+y"

# Just putting things together for easy display:
shiny::tags$div(class = 'flexbox',


19 thoughts on “Selecting a default value in an R plotly plot using a selectize box via crosstalk in R, using static html not shiny”

  1. You can directly manipulate the selectize boxes that crosstalk filter_select ouputs using javascript, the trick is triggering it on load like so:

    function filter_default() {
        document.getElementById("filter").getElementsByClassName("selectized")[0].selectize.setValue("a", false);
    window.onload = filter_default;
  2. Just to complement the accepted answer, which did function in the RStudio viewer in my case, but not in Chrome/Edge/IE/Firefox: the jQuery event Document.ready solved the problem (idea from this thread)

    $(document).ready(function() {
        document.getElementById("filter").getElementsByClassName("selectized")[0].selectize.setValue("a", false);

Leave a Comment