Extracting the exact coordinates of a mouse click in an interactive plot
I used ggplot2. Besides the materials at https://shiny.rstudio.com/articles/plot-interaction.html, I'd like to mention the following:
Firstly, when you create the plot, don't use "print( )" within "renderPlot( )", or the coordinates would be wrong. For instance, if you have the following in UI:
plotOutput("myplot", click = "myclick")
The following in the Server would work:
output$myplot <- renderPlot({ p = ggplot(data = mtcars, aes(x=mpg, y=hp)) + geom_point() p})
But the clicking coordinates would be wrong if you do:
output$myplot <- renderPlot({ p = ggplot(data = mtcars, aes(x=mpg, y=hp)) + geom_point() print(p)})
Then, you could store the coordinates by adding to the Server:
mydata = reactiveValues(x_values = c(), y_values = c())observeEvent(input$myclick, { mydata$x_values = c(mydata$x_values, input$myclick$x) mydata$y_values = c(mydata$y_values, input$myclick$y)})
In addition to X-Y coordinates, when you use facet with ggplot2, you refer to the clicked facet panel by
input$myclick$panelvar1