【问题标题】:How do I produce partial graphics in R-Shiny output?如何在 R-Shiny 输出中生成部分图形?
【发布时间】:2015-08-26 21:49:39
【问题描述】:

我希望我能简明扼要地解释一下。我有一个 R 函数,它运行生态模拟并返回输出列表(时间步长、人口规模、死亡率历史、后代数量等)。我想在某些情况下减慢图形输出,以便学生可以看到人口动态。应该显示绘图轴和标题,然后在 0.5 秒内出现代表累积后代的第一行,然后在 0.5 秒后出现第二行累积后代,然后在 0.5 秒后出现第三行,直到整个新后代队列已经绘制在“模拟”的末尾。

问题是应用程序要等到整个图像被渲染后才会显示,所以我无法向学生展示“减慢”的人口动态。输出图是空白的,直到所有这些 0.5 秒的延迟都完成,然后它会立即渲染。甚至在 for() 循环之前的图形调用也会被抑制,直到循环结束。下面的代码示例不完整,正在进行中的版本。

这是我的服务器代码——如果您取消注释 renderPlot 命令中的 dev.new() 调用,应用程序将完全按预期工作,除了输出在新的图形设备中,而不是在 Shiny 应用程序绘图窗口中:

shinyServer(function(input, output) {

observe({
    if(input$runSim == 0) return()
    isolate({
        sim <- reactive({
            switch(input$sim,
                   dorriefish = {
                        df.sim(input$S.df, input$p.df, show=FALSE)
                   }    # end case dorriefish
            )   # end switch(input$sim)
        })  # end reactive()

        output$modl.plot <- renderPlot({
            switch(input$sim,
                dorriefish = {
                    if (input$reps.df == 1)
                    {
                        # dev.new()
                          opar <- par(no.readonly=TRUE)                             
                        len <- length(sim()$offspring.t)
                        par(fig=c(0,1,0.1,0.9), xpd=NA)
                        plot(sim()$offspring.t, type="n", xlab="Time steps", ylab="Cumulative Doriefish offspring",
                            xlim=c(1, max(len, length(sim()$mass))))
                        mtext("Dorriefish living per time step (green = alive, red = dead):", side=3, at=(max(len)/2)+0.5,
                            line=4.2)
                         for(i in 1:nrow(sim()$mhistory))
                        {
                            z <- rep("green", length(sim()$mass))
                            z[sim()$mhistory[i,]] <- "red"
                            points(seq(1,len, length=length(sim()$mass)), rep(max(1.18*sim()$offspring.t), length(sim()$mass)),
                                pch=21, col="black", bg=z, cex=2.5)
                            lines(sim()$offspring.t[1:i], type="h")
                            Sys.sleep(0.5)
                        }
                        txt <- paste("Total offspring:", sim()$offspring,
                          "     Time to cohort extinction:", length(sim()$offspring.t), "time steps.")
                        mtext(txt, side=1, at=0, line=5, adj=0)
                        par(opar)

                    } # end if(input$reps.df == 1)
                }  # end case dorriefish
            )   # end switch(input$sim)
        })  # end renderPlot()

    })  # end isolate()
})  # end observe()

})  # end shinyServer()

这是用户界面代码:

library(shiny)

shinyUI(
fluidPage(
    titlePanel("BIOL 330 ecological simulations"),
    sidebarLayout(
        sidebarPanel("",
            helpText(HTML("<h3 style='text-align:center;'>Control Panel</h3>"), align='center'),
            tags$hr(style='height:2px; border-width:0; color:gray; background-color:gray'),

            # choose a simulation from a drop down menu
            selectInput("sim", HTML("<b>Select a simulation to explore:</b>"),
                # list the simulations available
                c("No simulation selected (Introduction)" = "none",
                "Dorriefish growth/reproduction trade-offs" = "dorriefish",
                "Optimal foraging" = "optfor")
            ),
            tags$hr(style='height:2px; border-width:0; color:gray; background-color:gray'),

            conditionalPanel(condition="input.sim=='dorriefish'",
                helpText(HTML("<b>Simulation model parameters:</b>")),
                sliderInput("S.df", label=div(HTML("Specify <em>S</em>, the switch point mass (g) for
                    transition from somatic growth to reproduction:")),
                    min = 1, max = 50, value = 10, step=5),
                sliderInput("p.df", label=div(HTML("Specify <em>p</em>, the probability of mortality
                by predation in any given time step:")),
                    min = 0, max = 1, value = 0.12, step=0.01),
                sliderInput("reps.df", label=div(HTML("Specify the number of full simulations to
                    run:")), min = 1, max = 100, value = 1, step=1)
            ),

            # bottom controls common to all panels
            conditionalPanel(condition="input.sim!='none'",
                tags$hr(style='height:2px; border-width:0; color:gray; background-color:gray'),
                fluidRow(column(4, actionButton("runSim", "Run simulation")),
                    column(4, actionButton("saveSim", "Save output file")),
                    column(4, actionButton("printSim", "Save/print plot"))),
                tags$hr(style='height:2px; border-width:0; color:gray; background-color:gray')
            )
        ),

        mainPanel("",

            # no model selected-- show information page
            conditionalPanel(condition="input.sim=='none'",
                includeHTML("www/simNoneText.html")
            ),

            tabsetPanel(id="outTabs", type="tabs",
                tabPanel("Plot", plotOutput("modl.plot")
                ),
                tabPanel("Summary"
                ),
                tabPanel("R Code"

                )
            )
        )
    )
)
)

所以重复我的问题,我怎样才能让服务器显示每个时间步的累积后代数,暂停 0.5 秒,而不是显示下一个,直到显示所有模拟时间步?

谢谢,最好的问候, ——迈克 C.

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    我已尝试阅读您的代码,这就是我所看到的:

    我建议你使用uiOutput()函数来显示输出,这样ui.R会更清晰,同时将计算放在server.R

    要模拟人口增长(或其他任何事情)时的步骤,您可以在 server.R 中一次计算所有步骤,然后在 for() 循环内仅显示一些数据,就像在 server.R 内一样

    output$plot <- renderUI({
        ### here calculate the results all at once and save it to a variable
        result <- calculations
    
        for(i in 1:dim(result)[1]){
            Sys.sleep(0.5) # time to wait to perform each plot
            ### here you put the code to only get some results of
            ### the calculation you've perfomed earlier
            ggplot(results[i,...], ...)
        }
    })
    

    【讨论】:

      猜你喜欢
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      • 2023-03-23
      • 2017-08-09
      相关资源
      最近更新 更多