Skip to content

Instantly share code, notes, and snippets.

@aagarw30
Created April 1, 2020 08:00
Show Gist options
  • Save aagarw30/1a86725add60b9dae42fbb44b8e94817 to your computer and use it in GitHub Desktop.
Save aagarw30/1a86725add60b9dae42fbb44b8e94817 to your computer and use it in GitHub Desktop.
Interactive data point selection with ggplotly/plotly charts
## Load required packages
library(plotly)
library(ggplot2)
library(shiny)
## Defining a key column in mtcars which will be used for event handling in event_data()
mtcars$key <- row.names(mtcars)
### Ui code begins below
ui <- fluidPage(
h1("Demo - Interactive data point selection with ggplotly/plotly charts"),
h4("Subset the dataset using the data points selected from the chart. Drag and select one or multi data points"),
br(),
## Plotly plot display
plotlyOutput("plot"),
## Data point information display post click
verbatimTextOutput("click")
)
## Server side code begins below
server <- function(input, output, session) {
## ggplotly scatter plot
output$plot <- renderPlotly({
myplot <- ggplot(mtcars, aes(x = mpg,
y = wt,
key = key)) + geom_point()
## in above code line, use the argument key inside ggplot which will be used for event handling
ggplotly(myplot) %>%
layout(dragmode = "select")
})
## returns the data related to data points selected by the user
output$click <- renderPrint({
## Click_data will have the keys (row identifiers) corresponding to selected data points
click_data <- event_data("plotly_selected")
## Event mode options. There are many more to experiment
## plotly_click - click on one data point
## Plotly_selected - multi point select
if(is.null(click_data))
"No data points selected on scatter plot..."
else
filter(mtcars, key %in% click_data$key) %>% select(-key)
## Subsetting in above step based on selected data points and removing the key column
})
}
shinyApp(ui, server)
@aagarw30
Copy link
Author

aagarw30 commented Jul 10, 2023 via email

@ZeroLi-Bio
Copy link

Hello, I figured out a way and forked your gist.
Thank you!

@aagarw30
Copy link
Author

aagarw30 commented Jul 11, 2023 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment