Update large plots in Shiny without Re-Rendering

后端 未结 1 1590
醉酒成梦
醉酒成梦 2020-12-18 10:42

General Goal

I would like to be able to use RShiny to quickly plot large amounts of data that comes from R, and then make small modifications or add

相关标签:
1条回答
  • 2020-12-18 11:25

    Here is a solution with plotly. It does re-render the entire plot, but it's fast so perhaps will still meet your requirements. I think you'll see that introducing Plotly should not majorly disrupt your workflow.

    Note that I use Plotly's WebGL function for speed. The example below is 100000 points. I've also included an example of how you would convert your existing ggplot2object. For Plotly click events, see this.

    library(shiny)
    library(dplyr)
    library(plotly)
    library(ggplot2)
    
    ui <- fluidPage(
    
      titlePanel("Highlight nearby points"),
    
      sidebarLayout(
        sidebarPanel(width=3,
          p("Click on a point. Nearby points will be highlighted.")
        ),
    
        mainPanel(
          plotlyOutput("plot")
        )
      )
    )
    
    # Data
    df <- tibble(x = runif(1e+05,1,100), y = runif(1e+05,1,100))
    
    server <- function(input, output, session) {
    
      output$plot <- renderPlotly({
    
        # Gather click data
        event.data <- event_data("plotly_click")
    
        # Plotly object
        p <- plot_ly(df, x = ~x, y = ~y, type = "scatter", mode = "markers") 
    
        # Alternative: use existing ggplot
    
        # gg <- ggplot(df, aes(x = x, y = y)) +
        #   geom_point()
        # 
        # p <- plotly_build(gg)
    
        # End alternative
    
        # Check for click data
        if(!is.null(event.data)) {
    
          # If click data exists, create new markers based on range criteria and use a different color
          d <- filter(df,
                      x < event.data$x+10 & x > event.data$x-10,
                      y < event.data$y+10 & y > event.data$y-10)
          p <- add_markers(p, data = d, color = I("red"))
    
        }
    
        # Use webGL for faster ploting of many points
        p %>% toWebGL()
    
      })
    }
    
    # Run the application 
    shinyApp(ui = ui, server = server)
    
    0 讨论(0)
提交回复
热议问题