【问题标题】:Cache a base ggplot in a shiny app and allow modification of layers dynamically (leafletProxy equivalent for ggplot)在闪亮的应用程序中缓存基本 ggplot 并允许动态修改图层(leafletProxy 等效于 ggplot)
【发布时间】:2017-01-29 12:31:14
【问题描述】:

如果显示的基本数据集很大(下面的示例工作代码),则在闪亮的应用程序中向/从 ggplot 添加/删除层可能需要一段时间。

问题是:

有没有办法缓存 ggplot(基本图)并添加/删除/修改额外(动态)图层,而无需在闪亮的应用程序中重做整个图? 也就是说,一个等效于 leafletProxy() 的函数用于传单地图(参见 leaflet Rstudio webpage 中的工作示例)。

stackoverflow thread 中提出了一种可能的解决方法(下例中的选项 B),但是,它不会阻止 ggplot 重做整个绘图。

示例工作代码:

library(shiny)
library(ggplot2)

shinyApp(
  shinyUI(
    fluidPage(
      sidebarLayout(
        sidebarPanel(
          checkboxInput("line", "Add line")
        ),
        mainPanel(
          plotOutput("plot")
        )
      )
    )
  ),
  shinyServer(function(input, output, session) {
    data(diamonds)
    vals <- reactiveValues(pdata=ggplot())

    observeEvent(input$line, {
      p <- ggplot(diamonds, aes(x=carat, y=depth)) + geom_point()
      if (input$line){
        lineData <- data.frame(x=c(1, 4), y = c(60, 75))
        p <- p + geom_line(data = lineData, aes(x=x, y=y), color = "red")
      }
      vals$pdata <- p
    })
    # Option A ------
    # output$plot <- renderPlot({
    #     vals$pdata
    # })
    #
    # Option B ------
    observeEvent(vals$pdata,{
      output$plot <- renderPlot({
        isolate(vals$pdata)
      })
    })

  })
)

【问题讨论】:

    标签: r ggplot2 shiny


    【解决方案1】:

    您总是可以只制作两个图,然后使用条件来选择要显示的图。初始渲染很慢,但在初始化后效果很好。

    library(shiny)
    library(ggplot2)
    
    shinyApp(
      shinyUI(
        fluidPage(
          sidebarLayout(
            sidebarPanel(
              checkboxInput("line", "Add line", value = TRUE)
              ),
            mainPanel(
              conditionalPanel(condition = 'input.line == false',
                               plotOutput("plot1"),
                               ),
              conditionalPanel(condition = 'input.line == true',
                               plotOutput("plot2"),
                               ),
              )
            )
          )
        ),
      shinyServer(function(input, output, session) {
        #data(diamonds)
    
    
        # Option C -------
        output$plot1 <- renderPlot({
          ggplot(diamonds, aes(x=carat, y=depth)) + geom_point()
        })
        output$plot2 <- renderPlot({
          lineData <- data.frame(x=c(1, 4), y = c(60, 75))
    
          ggplot(diamonds, aes(x=carat, y=depth)) + 
            geom_point()+
            geom_line(data = lineData, aes(x=x, y=y), color = "red")
        })
    
      })
    )
    

    【讨论】:

      猜你喜欢
      • 2017-04-09
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 2013-06-20
      • 2022-06-25
      • 2018-05-21
      • 2013-07-02
      • 1970-01-01
      相关资源
      最近更新 更多