1

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)

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

when I have more than one plotly plots, how can I give some id so that to refer to the one clicked?
You can set an id via the source argument in plot_ly or ggplotly and call the events for a specific plot via the source argument of event_data. See my edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.