在 renderPlotly 单击事件中使用 nearPoints 时出现闪亮错误 [英] Shiny error while using nearPoints in renderPlotly click event

查看:51
本文介绍了在 renderPlotly 单击事件中使用 nearPoints 时出现闪亮错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用来自点击事件的数据获取 nearPoints.

I would like to fetch nearPoints using the data from a click event.

我从 Shiny 网页 中找到了以下片段它按预期工作正常.

I have found the below snippet from the Shiny webpage and it works fine as expected.

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.但是,它不起作用.

I tried to mimic the above the approach to identify the nearPoints in the Plotly plots using the click event data. However, it did not work.

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

知道如何将坐标信息传递给绘图吗?

Any idea on how to pass the coordinate information to the plotly plot?

推荐答案

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

I am not sure on how to do this with the nearPoints function, but is using that function really necessary? You could find the points that are within a threshold of the clicked point as well with the following code:

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

希望这会有所帮助.

这篇关于在 renderPlotly 单击事件中使用 nearPoints 时出现闪亮错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆