Interactive plotting in shiny using mouse clicks

前端 未结 1 707
独厮守ぢ
独厮守ぢ 2021-02-03 15:42

I am doing a project where I use the shiny server and connect R to mongodb to fetch results from database and display it dynamically.

However, I face the following probl

相关标签:
1条回答
  • 2021-02-03 16:36

    Here's a simple example that demonstrates the behavior you want, just run this code (or save as a file and source it). This code uses the new observeEvent function that debuted in Shiny 0.11, which just hit CRAN over the weekend.

    The basic idea is that we track two reactive values, click1 and range. click1 represents the first mouse click, if any exists; and range represents the x-values of both mouse clicks. Clicking on the plot simply manipulates these two reactive values, and the plotting operation reads them.

    library(shiny)
    
    ui <- fluidPage(
      h1("Plot click demo"),
      plotOutput("plot", clickId = "plot_click"),
      actionButton("reset", "Reset zoom")
    )
    
    server <- function(input, output, session) {
      v <- reactiveValues(
        click1 = NULL,  # Represents the first mouse click, if any
        range = NULL    # After two clicks, this stores the range of x
      )
    
      # Handle clicks on the plot
      observeEvent(input$plot_click, {
        if (is.null(v$click1)) {
          # We don't have a first click, so this is the first click
          v$click1 <- input$plot_click
        } else {
          # We already had a first click, so this is the second click.
          # Make a range from the previous click and this one.
          v$range <- range(v$click1$x, input$plot_click$x)
          # And clear the first click so the next click starts a new
          # range.
          v$click1 <- NULL
        }
      })
    
      observeEvent(input$reset, {
        # Reset both the range and the first click, if any.
        v$range <- NULL
        v$click1 <- NULL
      })
    
      output$plot <- renderPlot({
        plot(cars, xlim = v$range)
        if (!is.null(v$click1$x))
          abline(v = v$click1$x)
      })
    }
    
    shinyApp(ui, server)
    
    0 讨论(0)
提交回复
热议问题