Search code examples
rshinyr-plotly

ggplotly get data values of clicks


How can I get the x and y coordinates of an interactive map created with ggplot and plotly in R shiny? I want to get the x axis values and based on that display other data. Here is some dummy code.

library(shiny)
library(plotly)
library(ggplot2)


ui <- fluidPage(

       plotlyOutput("distPlot")
    
 )


server <- function(input, output) {

output$distPlot <- renderPlotly({
    gg1 = iris %>% ggplot(aes(x = Petal.Length, y = Petal.Width)) + geom_point()
    ggplotly(gg1)
    })
}

 shinyApp(ui = ui, server = server)

Solution

  • Maybe this is what your are looking for. The plotly package offers a function event_data() to get e.g. the coordinates of click events inside of a shiny app. See here. If you have multiple plots you could use the source argument to set an id and to get the event data for a specific plot:

    library(shiny)
    library(plotly)
    library(ggplot2)
    
    
    ui <- fluidPage(
      
      plotlyOutput("distPlot"),
      verbatimTextOutput("info")
      
    )
    
    
    server <- function(input, output) {
      
      output$distPlot <- renderPlotly({
        gg1 = iris %>% ggplot(aes(x = Petal.Length, y = Petal.Width)) + geom_point()
        ggplotly(gg1, source = "Plot1")
      })
      
      output$info <- renderPrint({
        d <- event_data("plotly_click", source = "Plot1")
        
        if (is.null(d)) {
          "Click events appear here (double-click to clear)"
        } else {
          x <- round(d$x, 2)
          y <- round(d$y, 2)
          cat("[", x, ", ", y, "]", sep = "")
        }
      })
    }
    
    shinyApp(ui = ui, server = server)