Sanathoi Gurumayum Sanathoi Gurumayum - 20 days ago 8
R Question

Shiny Interactive Graph plot showing row names

I am using Shiny and ggplot2 for an interactive graph. I also used "plot1_click" to get x and y locations.

output$selected <- renderText({
paste0("Value=", input$plot1_click$x, "\n",
"Names=", input$plot1_click$y) }) #how to get names???

This is part of server code. Here what I want is, instead of printing the "y" coordinates, I want to print the corresponding name written in y-axis. Is there any possible way for it??

Answer Source

As far as I know clicking points is not supported in plotOutput. Click events will only return coordinates of the click location. Those coordinates can however be used to figure out the nearest point.

This shiny app from the shiny gallery pages uses the function shiny::nearPoints which does exactly that. Here is a minimal example.


    plotOutput("plot", click = "plot_click"),
  server = function(input, output, session){
    output$plot <- renderPlot({ggplot(mtcars, aes(wt, mpg)) + geom_point()})
    output$print = renderPrint({
        mtcars,             # the plotting data
        input$plot_click,   # input variable to get the x/y coordinates from
        maxpoints = 1,      # only show the single nearest point 
        threshold = 1000    # basically a search radius. set this big enough 
                            # to show at least one point per click

The verbatimTextOutput shows you the nearest point to the clicked location. Notice that nearPoints only works with ggplots like that. But the help page suggests that there is also a way to use this with base graphics.