Home > OS >  How to get x category from click in shiny
How to get x category from click in shiny

Time:10-14

How can I get the category (x-axis info) from a bar plot from a click in shiny. See the app below. I would like output$cut to display the cut type when a user clicks on one of the bars in the plot.

library(shiny)
library(ggplot2)
library(dplyr)

ui <- fluidPage(
  plotOutput('diamonds', click = "click"),
  textOutput('cut')
)

server <- function(input, output, session) {
  output$diamonds <- renderPlot({
    diamonds %>% 
      ggplot()  
      geom_bar(aes(cut))
  })
  
  output$cut <- renderText({
    req(input$click)
    
    # This isn't meaningful
    x <- round(input$click$x, 2)
    y <- round(input$click$y, 2)
    cat("[", x, ", ", y, "]", sep = "")
    
    # and this doesn't work either
    # nearPoints(diamonds, input$click, xvar = "cut")
  })
}

shinyApp(ui, server)

CodePudding user response:

The x value you get from input$click$x corresponds to the factor that was clicked on. This needs to be rounded to a whole number and can be used to obtain the factor name.

The factor name can be used to filter the diamonds dataset.

x <- round(input$click$x) ## this will return a whole number corresponding to the factor that was clicked on.

##filter for the selected cut by using levels to get the name of the factor.
selected_cut <- diamonds %>% filter(cut == levels(diamonds$cut)[x])

  • Related