Retrieving source data information from a barplot in R shiny interactively

一世执手 提交于 2019-12-11 17:24:10

问题


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.


回答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)


来源:https://stackoverflow.com/questions/48591012/retrieving-source-data-information-from-a-barplot-in-r-shiny-interactively

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