Skip to content

Commit c3388a6

Browse files
committed
better shiny app example if accumulating event data
1 parent b73f190 commit c3388a6

File tree

2 files changed

+29
-21
lines changed
  • inst/examples/shiny

2 files changed

+29
-21
lines changed

inst/examples/shiny/event_data_click_map/app.R

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
# git checkout feature/transmit
2-
# R CMD install ./
3-
41
library(shiny)
52
library(plotly)
63

inst/examples/shiny/event_data_persist/app.R

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,33 +2,44 @@ library(shiny)
22
library(plotly)
33

44
ui <- fluidPage(
5-
plotlyOutput("plot"),
6-
verbatimTextOutput("data")
5+
plotlyOutput("p"),
6+
tableOutput("table")
77
)
88

9-
mtcars$id <- row.names(mtcars)
10-
119
server <- function(input, output, session) {
1210

13-
output$plot <- renderPlotly({
14-
plot_ly(mtcars, x = ~disp, y = ~mpg) %>%
15-
add_markers(key = ~id) %>%
16-
layout(dragmode = "select") %>%
17-
highlight("plotly_selected")
11+
# keep track of which cars have been hovered on
12+
cars <- reactiveVal()
13+
14+
# On hover, the key field of the event data contains the car name
15+
# Add that name to the set of all "selected" cars
16+
observeEvent(event_data("plotly_hover"), {
17+
car <- event_data("plotly_hover")$key
18+
cars_old_new <- c(cars(), car)
19+
cars(unique(cars_old_new))
1820
})
1921

20-
selected <- reactiveVal(rep(FALSE, nrow(mtcars)))
22+
# clear the set of cars when a double-click occurs
23+
observeEvent(event_data("plotly_doubleclick"), {
24+
cars(NULL)
25+
})
2126

22-
selected_data <- reactive({
23-
ed <- event_data("plotly_selected")
24-
if (is.null(ed)) return(NULL)
25-
new <- mtcars[["id"]] %in% ed[["key"]]
26-
selected(selected() | new)
27-
mtcars[selected(), ]
27+
output$p <- renderPlotly({
28+
29+
# if the car is selected, paint it red
30+
cols <- ifelse(row.names(mtcars) %in% cars(), "red", "black")
31+
32+
mtcars %>%
33+
plot_ly(
34+
x = ~wt, y = ~mpg,
35+
key = row.names(mtcars),
36+
color = I(cols)
37+
) %>%
38+
add_markers()
2839
})
2940

30-
output$data <- renderPrint({
31-
selected_data()
41+
output$table <- renderTable({
42+
filter(mtcars, row.names(mtcars) %in% cars())
3243
})
3344

3445
}

0 commit comments

Comments
 (0)