Is there a way to render a more detailed table after plotly_click?

Viewed 61

my problem is pretty simple yet I can't seem to find a solution.

Given the simultated data frame below, I am looking to render a table after clicking on a bar in the barplot generated with 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
    })
    
  }
)

The rendered table gives me probably what I should expect but I need more information in there like the rest of the variables from the original data frame used to plot.

Any ideas? I would appreciate it very much.

ps. I am aware this works fine with ggplot but I am intrigued by plotly.

1 Answers

Assuming xou want to output filtered Data concering the point, i can offer this solution. event.data gives you the x and y Coordinates. You can use these to filter the data Points as you defined x as Deliv and y as 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
    })
    
  }
)
Related