Shiny + GGplot - mouse click coordinates

3.1k Views Asked by At

I have a doubt in shiny ploting a GGPlot Bar Graph. I can recognize coordinates of mouse click (x,y), but I need know a value of bar (x-axis) to refresh the graph with parameter and simulate a drill-down. Anyone can help me?

library(shiny)
library(ggplot2)

ui <- fluidPage(
  plotOutput("plot", click = "GGPlot_click")
)

server <- function(input, output, session) {
  v <- reactiveValues(
    click1 = NULL  
  )

  # Handle clicks on the plot
  observeEvent(input$GGPlot_click, {
      v$click1 <- input$GGPlot_click
  })

  observeEvent(input$reset, {
    v$click1 <- NULL
  })

  output$plot <- renderPlot({
    pg <- ggplot(cars, aes(speed, dist)) +  geom_bar(stat="identity")

    print(pg)
    if (!is.null(v$click1$x))
      print(paste(v$click1$x, v$click1$y, sep = " / "))
      #print(v$click1)
  })
}

shinyApp(ui, server)

images and code: https://github.com/faustobranco/stackquestion

1

There are 1 best solutions below

0
On BEST ANSWER

I find a way to resolve:

imagens and codes: https://github.com/faustobranco/StackQuestions

library(shiny)
library(ggplot2)

ui <- fluidPage(
  plotOutput("plot", click = "plot_click"),
  verbatimTextOutput("info")
)

server <- function(input, output, session) {

  output$plot <- renderPlot({
    ggplot(cars, aes(speed, dist)) +  geom_bar(stat="identity")
  })

  output$info <- renderText({
    xy_str <- function(e) {
      if(is.null(e)) return("NULL\n")
      paste0("x=", round(e$x, 1), "\n")
    }
    x_Numeric <- function(e) {
      if(is.null(e)) return(0)
      round(e$x, 1)
    }    

    paste0(
      "click: x = ", xy_str(input$plot_click),
      "Nearest x-axis[?]: ", toString(which(abs(as.numeric(cars$speed)-as.numeric(x_Numeric(input$plot_click)))==min(abs(as.numeric(cars$speed)-as.numeric(x_Numeric(input$plot_click))))))
    )

  })  
}

shinyApp(ui, server)