是否可以使用 NearPoints 从 ggplot stat_qq 图中读取点?

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

我正在构建一个闪亮的应用程序,我正在尝试使用 nearPoints 检测 stat_qq 图中的点击点。我正在努力让这段代码正常工作,但我总是以错误消息告终: nearPoints: not able to automatically infer xvar from coordinfo.

我试图在 nearPoints 函数中指定 xvar 和 yvar,但是,对于 qq-plot,我只需要指定一个变量。无论我指定哪个,另一个都会生成错误。

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)

有人知道我错过了什么吗?

您必须使用 ggplot_build 来获取渲染数据。

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())

}