【问题标题】:Subset a dataframe based on plotly click event根据情节点击事件对数据框进行子集
【发布时间】:2019-06-23 22:14:23
【问题描述】:

我有下面的数据框:

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

还有一个简单的闪亮应用程序,可以从中创建一个情节直方图。我的目标是单击直方图的一个条形图并在与该条形图对应的数据表中显示Name。例如,如果我单击第一个栏 3,我将获取一张包含 John 和 Bob 姓名的表格。

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)

【问题讨论】:

  • 如果再添加一列计数2,2,1,这很容易。 Bcoz 当您单击绘图时,您将从直方图中获得计数,而不是实际值。你还好吗?
  • 我已经为你添加了一个解决方案。请让我知道你的看法。

标签: r plotly dt


【解决方案1】:

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

    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)

解决方案的屏幕截图:

【讨论】:

  • 我喜欢您的解决方案,如果我使用 s$x 而不是 s$y 并且不添加其他列怎么办?
  • 我不确定,因为有时你会得到像 3.5 这样的值,而这在你的数据集中并不存在。
猜你喜欢
  • 2021-06-03
  • 2013-08-15
  • 2017-08-17
  • 2019-10-16
  • 2022-06-18
  • 1970-01-01
  • 2016-09-10
  • 1970-01-01
  • 2016-10-28
相关资源
最近更新 更多