3

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)
2
  • 1
    It is easy if you add one more column with count 2,2,1. Bcoz when you click on plot, you will get count from histogram not the actual values. Is it okay for you? Commented Jan 30, 2019 at 15:40
  • I have added a solution for you. Please let me know your views. Commented Jan 30, 2019 at 15:49

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

I like your solution what if I use s$x instead of s$y and do not add another column?
I am not sure because sometimes you get value like 3.5 which doesn't exist in your dataset.
MAYBE YOU COULD CHECK THIS stackoverflow.com/questions/73545778/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.