r - 有没有办法在plotly_click之后渲染更详细的表格?

标签 r shiny plotly

我的问题很简单,但我似乎找不到解决方案。

鉴于下面的模拟数据框,我希望在单击使用plot_ly生成的条形图中的一个条形后渲染一个表格。

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

data <- data.frame(c(1,2,3,4,5,6,7,8,9,10), 
                   c(74, 100,74,16,16,99,16, 40, 16, 16), 
                   c(1, 10,1,8,6,2,6,4,6,6), 
                   c(0,0,0,112,0,0,0,0,96,16))
colnames(data) <- c("Deliv", "Pr", "Pro", "Disc")


shinyApp(
  ui = fluidPage(
    plotlyOutput("plot"),
    DT::dataTableOutput('tb')),
  
  server = function(input, output) {
    
    output$plot <- renderPlotly({
      plot_ly(data,
              x = ~Deliv,
              y = ~Pr,
              type = "bar",
              source = "click")})
    
    output$tb <- renderDataTable({
      event.data <- event_data("plotly_click", source = "click")
      
      if(is.null(event.data) == T) return("NULL") else event.data
    })
    
  }
)

渲染的表格可能为我提供了我应该期望的内容,但我需要其中的更多信息,例如用于绘图的原始数据框中的其余变量。

有什么想法吗?我将非常感激。

ps。我知道这与 ggplot 配合得很好,但我对plotly很感兴趣。

最佳答案

假设xou想要输出有关这一点的过滤数据,我可以提供这个解决方案。 event.data 为您提供 xy 坐标。您可以使用这些来过滤数据点,因为您将 x 定义为 Deliv,将 y 定义为 Pr

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

data <- data.frame(c(1,2,3,4,5,6,7,8,9,10), 
                   c(74, 100,74,16,16,99,16, 40, 16, 16), 
                   c(1, 10,1,8,6,2,6,4,6,6), 
                   c(0,0,0,112,0,0,0,0,96,16))
colnames(data) <- c("Deliv", "Pr", "Pro", "Disc")


shinyApp(
  ui = fluidPage(
    plotlyOutput("plot"),
    DT::dataTableOutput('tb')),
  
  server = function(input, output) {
    
    output$plot <- renderPlotly({
      plot_ly(data,
              x = ~Deliv,
              y = ~Pr,
              type = "bar",
              source = "click")})
    
    output$tb <- renderDataTable({
      event.data <- event_data("plotly_click", source = "click")
      ####### SOLUTION HERE
      # corrected NULL as NULL Value
      if(is.null(event.data) == T) return(NULL)
      # Filter result via Data
      res <- data[event.data$x==data$Deliv & event.data$y==data$Pr,]
      return(res)
      ######## SOLUTION END
    })
    
  }
)

关于r - 有没有办法在plotly_click之后渲染更详细的表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69908943/

相关文章:

r - 是否可以在 Github Pages 上托管交互式 R Markdown 文件?

r - 在 dateRangeInput 或 dateInput 中仅显示月份以获得 Shiny 的应用程序 [R 编程]

R plotly : How to connect lines on polar/radar chart?

r - 在 Quarto/Rmarkdown 中包含透明 ggplot,无需保存到磁盘

r - 如何调用由 downloadHandler 中的 react 函数产生的图

r - 在 Shiny 中使用日历格式输入数字数据的方法?

javascript - 当数据链接到变量时,d3js 不进行绘图

r - 使用不带 ggplot 的 Plotly 和 R 堆积面积图

r - 安装Rcartogram程序包-错误消息

mysql - 如何在 RMysql 中检查表是否存在