@@ -2,33 +2,44 @@ library(shiny)
2
2
library(plotly )
3
3
4
4
ui <- fluidPage(
5
- plotlyOutput(" plot " ),
6
- verbatimTextOutput( " data " )
5
+ plotlyOutput(" p " ),
6
+ tableOutput( " table " )
7
7
)
8
8
9
- mtcars $ id <- row.names(mtcars )
10
-
11
9
server <- function (input , output , session ) {
12
10
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 ))
18
20
})
19
21
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
+ })
21
26
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()
28
39
})
29
40
30
- output $ data <- renderPrint ({
31
- selected_data( )
41
+ output $ table <- renderTable ({
42
+ filter( mtcars , row.names( mtcars ) %in% cars() )
32
43
})
33
44
34
45
}
0 commit comments