渲染内部ObserveEvent(动态绘图生成)

时间:2015-08-01 10:14:51

标签: r ggplot2 shiny

我尝试重新创建https://gist.github.com/wch/5436415/,但是通过按钮添加图表。我认为这需要我沿着这些行修改链接上的canvas.width = canvas.offsetWidth; canvas.height = canvas.offsetHeight; 代码(图表名相关变量是通过server.r创建的) -

reactiveValues

但是这似乎没有进入在observeEvent中创建图表本身的原始循环,这导致renderUI块中没有图表。

任何提示?

1 个答案:

答案 0 :(得分:6)

我并不真正理解你问题中的代码,所以我忽略了它,只是从gist中获取了Winston的代码,并使用按钮代替滑块。我希望这就是你的意思?另外,我确实必须在一个我不满意的观察者中使用渲染:/

runApp(shinyApp(
  ui = fluidPage(
    headerPanel("Dynamic number of plots"),

    mainPanel(
      actionButton("addplot", "Add plot"),
      uiOutput("plots")
    )
  ),
  server = function(input, output, session) {

    # A variable that keeps track of the number of plots we have
    values <- reactiveValues(
      numPlots = 1
    )

    # Whenever the "add plot" button is pressed, increment num plots by 1
    observeEvent(input$addplot, {
      values$numPlots <- values$numPlots + 1
    })

    # Dynamically generate the UI that creates all the plots
    output$plots <- renderUI({
      # Create a list of `plotOutput` objects (for each plot, use a unique ID)
      plot_output_list <- lapply(1:values$numPlots, function(i) {
        plotname <- paste("plot", i, sep="")
        plotOutput(plotname, height = 280, width = 250)
      })

      # Place all the plot outputs inside a shiny `tagList()`
      do.call(tagList, plot_output_list)
    })

    # Every time the number of plots changes (button is clicked),
    # re-generate the render functions for all the plots
    observeEvent(values$numPlots, {
      for (i in 1:values$numPlots) {
        local({
          my_i <- i
          plotname <- paste("plot", my_i, sep="")

          output[[plotname]] <- renderPlot({
            plot(1:my_i, 1:my_i,
                 xlim = c(1, values$numPlots),
                 ylim = c(1, values$numPlots),
                 main = paste("1:", my_i, ".  n is ", values$numPlots, sep = "")
            )
          })
        })
      }
    })
  }
))

希望有所帮助