串扰:在启动时更改 Plotly Graph

Crosstalk: Change Plotly Graph on Startup

我正在尝试通过 crosstalk 在我的 Rmarkdown 文档中更改 plotly 图表。这在原则上工作正常,但是,我想通过 JavaScript 将下拉列表设置为启动时的第一个元素。但是,此更改 不会 更新图表。如果我 运行 在呈现整个页面后使用相同的代码,或者使用延迟它会起作用。

因此,我假设更新 JavaScript 为 运行 时,plotly 图尚未呈现。 setTimeout 解决方案有效,但这感觉很糟糕。那么通知 plotly/crosstalk 输入发生变化的规范方式是什么?

在 gif 中,您会看到启动时绘图显示了整个范围,只有在更改为 b 然后更改为 a 后相应地更新了图表。我希望图表在启动时就已正确过滤。

代码

---
title: "Delay Plotly"
date: "1 2 2021"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE)
```
```{r libs}
library(crosstalk)
library(plotly)
```

```{r gen-data}
set.seed(1)
mdat <- data.frame(x = rep(LETTERS[1:6], 6),
                   y = sample(100, 36, TRUE),
                   fill = factor(rep(rep(1:3, each = 6), 2)),
                   grp = rep(letters[1:2], each = 18),
                   id = paste0("id", 1:36),
                   stringsAsFactors = FALSE)
sd <- SharedData$new(mdat, key = ~ id)

```

```{js}
$(function() {
   // set dropdown to first element
   // setTimeout(function() { // uncomment for workaround
      $('.selectized').each(function(idx, el) {
         const sel = this.selectize;
         const options = Object.keys(sel.options);
         sel.setValue(options[0]);
      });
   // }, 1000); // uncomment for workaround
})
```


```{r}
bscols(
   filter_select("grp",
                "Group:",
                sd,
                ~ grp, multiple = FALSE),
   plot_ly(sd) %>%
      add_trace(x = ~ x, y = ~ y, type = "bar", color = ~ fill,
                marker = list(line = list(color = "white", width = 1)) ## add border to see the 2 groups
                ) %>%
      layout(barmode = "stack"))
```

更顺畅的解决方法是使用 window.onload 挂钩。这避免了指定超时延迟的需要,而不是 $.ready 在 DOM 加载后触发,但整个页面已准备就绪。正是我所需要的,除非 plotly 中有专门用于此类操作的挂钩? plotly_afterplot 似乎是合适的人选。同样,这在 $.ready

上不可用
window.onload = function() {
   // set dropdown to first element
   $('.selectized').each(function(idx, el) {
      const sel = this.selectize;
      const options = Object.keys(sel.options);
      sel.setValue(options[0]);
   });