根据绘图点击事件对数据框进行子集 [英] Subset a dataframe based on plotly click event

查看:97
本文介绍了根据绘图点击事件对数据框进行子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据框如下:

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

和一个简单的闪亮应用程序,可以从中创建出可绘制的直方图.我的目标是单击直方图的条形图,并在与该条形图相对应的数据表中显示Name.例如,如果我单击第一个3栏,则将创建一个包含John和Bob名称的表.

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)

推荐答案

我正在通过修改您的data.frame来添加解决方案,如注释中所述:

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:

这篇关于根据绘图点击事件对数据框进行子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆