Skip to content

Instantly share code, notes, and snippets.

@ZeroLi-Bio
Forked from aagarw30/eventdata.R
Last active July 11, 2023 07:59
Show Gist options
  • Save ZeroLi-Bio/f8ee0054d7218e0aa3efe92f8662aabe to your computer and use it in GitHub Desktop.
Save ZeroLi-Bio/f8ee0054d7218e0aa3efe92f8662aabe to your computer and use it in GitHub Desktop.
Interactive data point selection with ggplotly/plotly charts
## Interactive data point selection with ggplotly/plotly charts, return selected key to variable
## 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()
row.names(mtcars) <- gsub(' ','.',row.names(mtcars))
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
mykey <<- renderText(click_data$key)
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)
mykey <- unlist(strsplit(mykey(),' '))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment