Subset a dataframe based on plotly click event

本小妞迷上赌 提交于 2019-12-11 14:25:36

问题


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)

回答1:


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:



来源:https://stackoverflow.com/questions/54443854/subset-a-dataframe-based-on-plotly-click-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!