I'm having an issue with plotly_hover option when trying to display information from the hover in another output in a shiny app.
I'm working with a plotly made from a ggplot that uses color aesthetic. I need to extract the hover information and display it in a separate text below the plot. I'm trying to extract the row number and use it to access the right row from the original data frame. The issue is it seems like the app is indexing from the beginning within each level of col variable. How can I get the indexing right when including the color aesthetic?
Below is a sample code that reproduces the issue. When I'm hovering over points with "a" value of col everything is fine but when I hover over the points with "b" it starts to index from the beginning (so that the first 4 points with col == "b" get "a" displayed in the text below the plot and only the last two points get the right value displayed).
Everything is displayed correctly if I remove the color aesthetic.
library(shiny) library(ggplot2) library(plotly) ui <- fluidPage( titlePanel("Plotly reprex app"), fluidRow( plotlyOutput("plotlyPlot", height = "700px"), verbatimTextOutput("memberDetails") ) ) server <- function(input, output, session) { df <- data.frame(x = 1:10, y = 1:10, col = c(rep("a", 4), rep("b", 6))) output$plotlyPlot <- renderPlotly({ t_p <- df %>% ggplot(aes(x = x, y = y, color = col, text = col)) + geom_point() ggplotly(t_p, tooltip = "text") }) output$memberDetails <- renderPrint({ event_data <- event_data("plotly_hover") point_index <- event_data$pointNumber[1] + 1 df_select <- df[point_index, ] cat("color is: ", df_select$col) }) } shinyApp(ui = ui, server = server) 