【问题标题】:Is there a way to render a more detailed table after plotly_click?有没有办法在 plotly_click 之后呈现更详细的表格?
【发布时间】:2021-12-22 19:06:57
【问题描述】:

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

鉴于下面的模拟数据框,我希望在单击使用 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 很感兴趣。

【问题讨论】:

    标签: r shiny plotly


    【解决方案1】:

    假设 xou 想要输出过滤后的数据,我可以提供这个解决方案。 event.data 为您提供 xy 坐标。您可以使用它们来过滤数据点,因为您将 x 定义为 Delivy 定义为 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
        })
        
      }
    )
    

    【讨论】:

      猜你喜欢
      • 2013-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-14
      • 2022-07-21
      • 2015-10-17
      • 1970-01-01
      • 2011-04-25
      相关资源
      最近更新 更多