Skip to content

Instantly share code, notes, and snippets.

@daattali
Last active April 16, 2024 15:16
Show Gist options
  • Save daattali/9440f0b278dbbf538b3587e026811426 to your computer and use it in GitHub Desktop.
Save daattali/9440f0b278dbbf538b3587e026811426 to your computer and use it in GitHub Desktop.
# I'm trying to let the user select points and paint them in a certain colour, and if the user clicks on a point then paint that point a different colour.
# It looks like the pointNumber and curveNumber data that plotly returns are different for the same points. I'm not sure how curveNumber works, but to me it doesn't make sense yet :)
# Any help is appreciated!
library(plotly)
library(shiny)
ui <- fluidPage(
plotlyOutput("plot")
)
server <- function(input, output, session) {
output$plot <- renderPlotly({
click_data <- event_data("plotly_click", source = "select")
select_data <- event_data("plotly_selected", source = "select")
data <- mtcars
data$col <- "black"
if (!is.null(select_data)) {
cat(str(select_data))
idx <- select_data$pointNumber + 1
data[idx, "col"] <- "blue"
}
if (!is.null(click_data)) {
cat(str(click_data))
idx <- click_data$pointNumber + 1
data[idx, "col"] <- "red"
}
p <- ggplot(data, aes(mpg, wt, col = I(col))) + geom_point()
ggplotly(p, source = "select")
})
}
shinyApp(ui, server)
# This is very similar to the previous file, but I tried applying Carson's advise of setting the key aesthetic to row names
library(plotly)
library(shiny)
ui <- fluidPage(
plotlyOutput("plot")
)
server <- function(input, output, session) {
output$plot <- renderPlotly({
click_data <- event_data("plotly_click", source = "select")
select_data <- event_data("plotly_selected", source = "select")
data <- mtcars
key <- row.names(data)
data$col <- "black"
if (!is.null(select_data)) {
cat(str(select_data))
idx <- select_data$pointNumber + 1
data[idx, "col"] <- "blue"
}
if (!is.null(click_data)) {
cat(str(click_data))
idx <- click_data$pointNumber + 1
data[idx, "col"] <- "red"
}
p <- ggplot(data, aes(mpg, wt, col = I(col), key = key)) + geom_point()
ggplotly(p, source = "select")
})
}
shinyApp(ui, server)
@asadow
Copy link

asadow commented Apr 16, 2024

Is it possible to maintain the same zoom state after click/selection?

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