Search code examples
rggplot2shinyinteractive

Is it possible to read points from a ggplot stat_qq plot with NearPoints?


I'm building a shiny app and I'm trying to detect clicked points in a stat_qq plot with nearPoints. I'm struggling to get this code working, I always end up with the error message: nearPoints: not able to automatically infer xvar from coordinfo.

I tried to specify xvar and yvar inside of the nearPoints function, however, for the qq-plot I only need to specify one variable. Whichever one I specify, the other one generates the error.

library(shiny)
library(ggplot2)

ui <- fluidPage(
  mainPanel(
    plotOutput("qqplot", click = "qqplot_click"),
    verbatimTextOutput("excl")
  ) 
)

server <- function(input, output, session) {

  rdata <- data.frame(rnorm(200, 20, 2), rep(TRUE, 200))
  names(rdata) <- c("data","Select")

  output$qqplot <- renderPlot({ggplot(data=rdata, aes(sample=data)) + stat_qq() + stat_qq_line()

  })


  excl.data <- eventReactive(input$qqplot_click, {
    res <- nearPoints(rdata, input$qqplot_click, yvar='data', allRows = TRUE)
    xor(rdata$Select, res$selected_)
  })

  output$excl <- renderPrint(excl.data())

}

shinyApp(ui, server)

Does anyone have an idea what I am missing?


Solution

  • You have to use ggplot_build to get the rendered data.

    server <- function(input, output, session) {
    
      rdata <- data.frame(rnorm(200, 20, 2), rep(TRUE, 200))
      names(rdata) <- c("data","Select")
    
      gg <- ggplot(data=rdata, aes(sample=data)) + stat_qq() + stat_qq_line()
      ggdata <- ggplot_build(gg)$data[[1]]
    
      output$qqplot <- renderPlot({
        gg
      })
    
      observe({
        print(input$qqplot_click)
      })  
    
      excl.data <- eventReactive(input$qqplot_click, {
        res <- nearPoints(ggdata, input$qqplot_click, 
                          xvar="theoretical", yvar="sample", allRows = TRUE)
        xor(rdata$Select, res$selected_)
      })
    
      output$excl <- renderPrint(excl.data())
    
    }