我正在尝试通过在我的文档中更改plotly
图表。这原则上可以正常工作,但是,我想将下拉菜单设置为启动时的第一个元素。但是,此更改不会更新图表。如果我在呈现整个页面后运行相同的代码,或者使用延迟它可以工作。crosstalk
Rmarkdown
JavaScript
因此,我假设在JavaScript
运行更新时,plotly
图形尚未呈现。该setTimeout
解决方案有效,但这感觉是hackis。那么通知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"))
```