Subset a dataframe based on plotly click event

2019-08-21 15:21发布

I have the data frame below:

Name<-c("John","Bob","Jack")
Number<-c(3,3,5)
NN<-data.frame(Name,Number)

And a simple shiny app which creates a plotly histogram out of it. My goal is to click on a bar of the histogram and display the Name in a datatable that correspond to this bar. For example if I click on the first bar which is 3 I will take a table with John and Bob names.

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

ui <- fluidPage(
  mainPanel(
    plotlyOutput("heat")
  ),
  DT::dataTableOutput('tbl4')
)

server <- function(input, output, session) {
  output$heat <- renderPlotly({
    p <- plot_ly(x = NN$Number, type = "histogram")
  })

  output$tbl4 <- renderDataTable({
    s <- event_data("plotly_click")
    if (length(s) == 0) {
      "Click on a bar in the histogram to see its values"
    } else {
      NN[ which(NN$Number==as.numeric(s[2])), 1]

    }
  })

}

shinyApp(ui, server)

标签: r plotly dt
1条回答
迷人小祖宗
2楼-- · 2019-08-21 15:29

I am adding the solution by modifying your data.frame as mentioned in the comment:

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

    ui <- fluidPage(
      mainPanel(
        plotlyOutput("heat")
      ),
      DT::dataTableOutput('tbl4')
    )

    server <- function(input, output, session) {
      output$heat <- renderPlotly({
        Name<-c("John","Bob","Jack")
        Number<-c(3,3,5)
        Count<-c(2,2,1)
        NN<-data.frame(Name,Number,Count)
        render_value(NN) # You need function otherwise data.frame NN is not visible
        p <- plot_ly(x = NN$Number, type = "histogram",source="subset") # set source so
                          # that you can get values from source using click_event

      })

      render_value=function(NN){
        output$tbl4 <- renderDataTable({
          s <- event_data("plotly_click",source = "subset")
          print(s)
          return(DT::datatable(NN[NN$Count==s$y,]))           
        })  
      }           
    }

    shinyApp(ui, server)

Screenshot from solution: Screenshot from output John and Bob Screenshot from output Jack

查看更多
登录 后发表回答