Borrowing the example from the linked question, you've got the following for starters:
---
output:
html_document
---
```{r echo=FALSE, message=FALSE, warning=FALSE}
library(plotly)
# 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"
)
```
You would paste the js from the accepted answer below the end of the r code, just as if you were making a new {r}
block beneath the first one.
```{js}
function filter_default() {
document.getElementById("filter").getElementsByClassName("selectized")
[0].selectize.setValue("a", false);
}
window.onload = filter_default;
```
To get this to work for you, there are a few arguments you'll likely need to change in the {js}
block.
1. First, you'll want to look back at what you used as the tag for your filter_select
element. This is the first argument. In the example above, filter_select("filter",
means that you have used "filter" as your tag for the filter.
Say we had instead used "lantern" as our id for the crosstalk filter. You would change document.getElementById("filter")
to document.getElementById("lantern")
in the {js}
.
2. Next, you'll want to look at what value is the default selection. In the example, the value is set to "a" with the selectize.setValue("a"
bit in the {js}
block. You have the ability to choose whatever value that exists in your data as a default. If, for example, you have source data:
other_dat<-data.frame(light=c("bulb","sun","biological"),amount=c(50,1000,3))
you could use (keeping in mind that we have chosen to tag our filter_select as "lantern"):
```{js}
function filter_default() {
document.getElementById("lantern").getElementsByClassName("selectized")
[0].selectize.setValue("bulb", false);
}
window.onload = filter_default;
```
to set the default filter_select value to "bulb", or:
```{js}
function filter_default() {
document.getElementById("lantern").getElementsByClassName("selectized")
[0].selectize.setValue("sun", false);
}
window.onload = filter_default;
```
to set the default value to "sun".