Reputation: 49
I would like to select points with box select in a ggplotly graph, and display the row contents in a table below the scatterplot.
There is an answer giving almost this here, but instead of displaying all data selected by the box select tool, it only displays one row which has been clicked upon.
How would I make a table appear below the scatterplot, which contains all data selected with the box select tool?
Code copied from the linked answer:
library(tidyverse)
library(plotly)
library(shiny)
d <- mtcars %>%
rownames_to_column("car")
# UI ----
ui <- fluidPage(plotlyOutput("plot"),
tableOutput("click"))
# server ----
server <- function(input, output) {
output$plot <- renderPlotly({
key <- d$car
p <- d %>%
ggplot(aes(x = disp, y = mpg, color = factor(cyl),
key = key)) +
geom_point(size = 4, alpha = 0.7)
ggplotly(p) %>%
event_register("plotly_click")
})
output$click <- renderTable({
point <- event_data(event = "plotly_click", priority = "event")
req(point) # to avoid error if no point is clicked
filter(d, car == point$key) # use the key to find selected point
})
}
# app ----
shinyApp(ui = ui, server = server)
Upvotes: 1
Views: 625
Reputation: 33500
We'll need to use plotly_selected
instead of plotly_click
.
Furthermore, please note the modified filter call using %in%
instead of ==
.
Please check the following:
library(plotly)
library(shiny)
library(datasets)
library(tibble)
d <- mtcars %>%
rownames_to_column("car")
# UI ----
ui <- fluidPage(plotlyOutput("plot"),
tableOutput("click"))
# server ----
server <- function(input, output) {
output$plot <- renderPlotly({
p <- d %>%
ggplot(aes(x = disp, y = mpg, color = factor(cyl),
customdata = car)) +
geom_point(size = 4, alpha = 0.7)
fig <- ggplotly(p)
event_register(fig, "plotly_selected")
fig
})
output$click <- renderTable({
plotly_event_data <- event_data(event = "plotly_selected", priority = "event")
req(plotly_event_data)
filter(d, car %in% plotly_event_data$customdata)
})
}
# app ----
shinyApp(ui = ui, server = server)
Upvotes: 2