我创建了以下 Rmarkdown 文件以基于单击交互式 ggplot 进行选择。
在javascript块中,我想使用从
交互式ggplot中的onclick事件获得的字母(A或B)而不是“A”。如果用户单击多边形 B,则“A”应变为“B”。
---
output:
html_document
---
```{r, echo = FALSE, message = FALSE}
library(ggplot2)
library(ggiraph)
# Rectangle A
group_A <- data.frame(x1 = 0,
x2 = 3,
y1 = 0,
y2 = 1,
r = "A")
# Polygon B
group_B <- data.frame(x = c(3,4,4,0,0,3),
y = c(0,0,2,2,1,1),
r = "B")
p <- ggplot() +
geom_rect_interactive(data = group_A,
aes(xmin = x1, xmax = x2, ymin = y1,
ymax = y2, data_id = r, onclick = r),
alpha = .1, color = "black") +
geom_polygon_interactive(data = group_B,
aes(x = x, y = y, data_id = r, onclick = r),
alpha = .1, color = "black") +
annotate("text", x = 0.1, y = .82,
label = "A",
fontface = 2, hjust = 0) +
annotate("text", x = 0.1, y = 1.82,
label = "B",
fontface = 2, hjust = 0) +
theme_void()
girafe(ggobj = p)
```
Javascript chunk:
```{js}
$(document).ready(function() {
document.getElementById("filter").getElementsByClassName("selectized"[0].selectize.setValue("A", false);
});
```
我怎样才能做到这一点?
请参阅通过 R 中的串扰使用选择框在 R 绘图中选择默认值,对于类似问题,使用静态 html 不闪亮。
编辑
更明确地说,我想根据所选矩形过滤下表:
```{r}
# example data
dat <- tibble::tribble(~value, ~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)
```
然后矩形question_filter
应该等于 ggplot 图中选择的矩形。我从链接的问题中获得了以下块,并想调整此块以根据所选矩形显示表格。
```{r}
library(crosstalk)
library(reactable)
# Initializing a crosstalk shared data object
plotdat <- highlight_key(dat)
# Filter dropdown
question_filter <- crosstalk::filter_select(
"filter", "Select a group to examine",
plotdat, ~value, multiple = F
)
plot <- reactable(plotdat)
# Just putting things together for easy
displayshiny::tags$div(class = 'flexbox',
question_filter,
shiny::tags$br(),
plot)
```