0

I have a barplot in R shiny. I want following:

When user clicks one "bar" in that barplot another box will pop up and show the data information from the used datadframe showing which data points contributed to create that "bar".

Code:

ui <- fluidPage(
  sidebarLayout(sidebarPanel(),
                mainPanel(plotOutput("p",click = "plot_click"),
                textOutput("info"))))

server <- function(input,output) {
    output$p <- renderPlot(ggplot(mtcars,aes(x=factor(carb),y=mpg))+
                         geom_bar(stat="summary",fun.y="mean"))
    output$info <- renderText(
      paste0("x=", input$plot_click$x, "\n",
           "y=", input$plot_click$y))
}
shinyApp(ui, server)

When I'm clicking on a bar, it is showing the (x,y) co-ordinate value. But I want to retrieve the corresponding factor(carb). How to get back source information back if I click on a bar. The ideal case would be: When user clicks on a bar which has carb=4, it should show the source information of the mtcars dataset with carb=4. But I'm stuck how to get the "carb=4" information interactively from that bar plot.

MrFlick
  • 195,160
  • 17
  • 277
  • 295

1 Answers1

1

Edited to be more specific to categorical x axis bar charts.

You need to translate the click value into the table you want. I've rounded the x value from the click to subset the mtcars data frame:

library(ggplot2)
library(shiny)

ui <- fluidPage(
  sidebarLayout(sidebarPanel(),
                mainPanel(plotOutput("p",click = "plot_click"),
                          textOutput("info"),
                          tableOutput("table"))))

server <- function(input,output) {
  output$p <- renderPlot(ggplot(mtcars,aes(x=factor(carb),y=mpg))+
                           geom_bar(stat="summary",fun.y="mean"))
  output$info <- renderText(
    paste0("x=", input$plot_click$x, "\n",
           "y=", input$plot_click$y))

  output$table <- renderTable({
    ##magic happens here##
    output$table <- renderTable({
     carb <- unique(mtcars$carb)
     carb <- carb[order(carb)]
     x <- carb[round(input$plot_click$x)]
     mtcars[mtcars$carb == x,]
   })

  })
}
shinyApp(ui, server)
Ryan Morton
  • 2,605
  • 1
  • 16
  • 19
  • That's fine. thanks, But it's not robust i.e if, instead of "1","2","3", the categories are "Name1","name2" like this rounding wouldn't work, unless you do a whole renumbering of those factors etc etc. Also, depending on the bar width we need to adjust how much rounding we need. I can not automate it in this rounding method.Your method is better than to have nothing but it's somewhat conservative. Looking for a robust method. Maybe there isn't any. Thanks by the way. Also, in case of stacked bar plot, it'll be even more complicated. – Arijit Pal Feb 02 '18 at 22:25
  • The point is: YOU have to translate the x,y click data do the graph as appropriate for that graph: https://shiny.rstudio.com/articles/plot-interaction-advanced.html – Ryan Morton Feb 05 '18 at 15:00