【问题标题】:Dynamically create plots based on number of uploaded files in Shiny根据 Shiny 中上传文件的数量动态创建绘图
【发布时间】:2015-11-06 20:06:42
【问题描述】:

我正在尝试开发一个闪亮的应用程序,用户可以在其中上传 csv 文件,这些文件随后由我的 R 脚本进行分析。因此,我想根据处理的文件数(每个文件一个图)显示动态的图数。

我发现this 问题非常有帮助,但我不知道提前的最大绘图数。这是我尝试过的:

shinyServer(function(input, output) {

  # Insert the right number of plot output objects into the web page
  output$densityPlots <- renderUI({
    plot_output_list <- lapply(1:length(input$file1$datapath), function(i) {
      plotname <- paste("densityPlot", i, sep="")
      plotOutput(plotname)
    })

    # Convert the list to a tagList - this is necessary for the list of items
    # to display properly.
    do.call(tagList, plot_output_list)
  })

  # Call renderPlot for each one. Plots are only actually generated when they
  # are visible on the web page.
  for (i in 1:length(input$file1$datapath)) {
    # Need local so that each item gets its own number. Without it, the value
    # of i in the renderPlot() will be the same across all instances, because
    # of when the expression is evaluated.
    local({
      my_i <- i
      plotname <- paste("densityPlot", my_i, sep="")
      output[[plotname]] <- renderPlot({
        plot(1)
      })
    })
  }
}

但是,它给了我这个错误:

  Error in .getReactiveEnvironment()$currentContext() : 
  Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)

我尝试将 for 循环放在输出函数中,但根本没有创建任何绘图。

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    我可以让它工作。正如here 所解释的那样,必须使用电抗导体来创建绘图。

    shinyServer(function(input, output) {
    
      createPlots <- reactive ({ 
        numberOfFiles <- length(input$files$datapath) 
        for (i in 1:numberOfFiles) {
          local({
            my_i <- i
            plotname <- paste("plot", my_i, sep="")
            File <- read.csv(input$files$datapath[my_i]) 
            output[[plotname]] <- renderPlot({
              result <- runDensity(File, f)
              plot(result$data, main=id, pch=19,cex=0.2, col= ColoursUsed[result$clusters])
            })
          })
        }
      })
    
      output$densityPlot <- renderUI({
    
        inFile <- input$files
        if (is.null(inFile))
          return(NULL)
        createPlots()
        numberOfFiles <- length(inFile$datapath) 
        plot_output_list <- lapply(1:numberOfFiles, function(i) {
          plotname <- paste("plot", i, sep="")
          plotOutput(plotname)
        })
    
        do.call(tagList, plot_output_list)
      })
    
    })
    

    【讨论】:

    • 我只是想补充一点,将 createPlots() 调用放在 renderUI 部分中的位置非常重要。它必须在 lapply 和 do.call(tagList,...) 之前调用
    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 2019-08-19
    • 2018-12-20
    • 2019-05-05
    • 2014-10-27
    • 2016-06-25
    • 2015-06-22
    • 2015-08-16
    相关资源
    最近更新 更多