r - 在 renderPlotly 单击事件中使用 closePoints 时出现 Shiny 错误

标签 r plotly shiny ropensci

我想使用点击事件中的数据获取 nearPoints

我从 Shiny webpage 中找到了以下代码片段正如预期的那样,它工作得很好。

output$plot <- renderPlot({
  d <- data()
  plot(d$speed, d$dist)
})

output$plot_clickedpoints <- renderPrint({
  # For base graphics, we need to specify columns, though for ggplot2,
  # it's usually not necessary.
  res <- nearPoints(data(), input$plot_click, "speed", "dist")
  if (nrow(res) == 0)
    return()
  res
})

我尝试模仿上述方法,使用点击事件数据来识别 Plotly 图中的 nearPoints。然而,这并没有奏效。

output$plot <- renderPlotly({
  d <- data()
  plot(d$speed, d$dist)
})

output$plot_clickedpoints <- renderPrint({
  # For base graphics, we need to specify columns, though for ggplot2,
  # it's usually not necessary.
  res <- nearPoints(data(), event_data("plotly_click"), "speed", "dist")
  if (nrow(res) == 0)
    return()
  res
})

关于如何将坐标信息传递到绘图的任何想法?

最佳答案

我不确定如何使用nearPoints函数来做到这一点,但是使用该函数真的有必要吗?您还可以使用以下代码找到单击点阈值内的点:

library(shiny)
library(plotly)
library(DT)

threshold_mpg = 3
threshold_cyl = 1

shinyApp(

  ui <- shinyUI(
    fluidPage(
      plotlyOutput("plot"),
      DT::dataTableOutput("table")
    )
  ),
  function(input,output){

    data <- reactive({
      mtcars
    })

    output$plot <- renderPlotly({
      d <- data()
      plot_ly(d, x= ~mpg, y=~cyl, mode = "markers", type = "scatter", source="mysource")
    })

    output$table<- DT::renderDataTable({

      event.data <- event_data("plotly_click", source = "mysource")
      print(event.data)
      if(is.null(event.data)) { return(NULL)}

      # A simple alternative for the nearPoints function
      result <- data()[abs(data()$mpg-event.data$x)<=threshold_mpg & abs(data()$cyl-event.data$y)<=threshold_cyl, ]
      DT::datatable(result)
    })
  }
)

希望这有帮助。

关于r - 在 renderPlotly 单击事件中使用 closePoints 时出现 Shiny 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45525310/

相关文章:

Plotly:同一图中的散点图和动画线图

html - 如何调整包含plotly的div以绘制尺寸,使其不与文档重叠

javascript - 使用 shinyjs 和 flexdashbord 动态显示/隐藏输入

r - shinydashboard:通过textInput过滤DT

r - 如何将 R Shiny 演示文稿导出为 pdf 或 html

r - 为三个输入参数的每个组合导出公式结果

function - R 的 "%in%"对于 Stata 的等效函数

r - 从稀疏表构建网络边缘表

r - 分两步计算列表中的元素

plot - 如何在 Julia 中绘制矢量场?