Shiny中动态绘图高度

17

我有一个闪亮的应用程序,其中绘图需要根据用户输入调整高度。 基本上,绘图可以具有一个、两个或四个子绘图。 当只有一个或两个时一切正常,但是当有四个时,子绘图会被压缩到太小的大小。 我尝试使用响应函数在服务器上给我计算出高度,但是我得到了这个错误:

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.)

我试图做的事情非常简化,这里是一个例子:

library(shiny)

ui <- fluidPage(

   fluidRow(
      column(2, 
             radioButtons( inputId = 'plotcount', label = 'Plot Count', 
                                 choices = c('1' = 1, 
                                             '2' = 2,
                                             '4' = 4
                                 ),
                           selected = '1'
             )
      ),
      column(10, 
             plotOutput( outputId = 'plots' )
      )
   )
)

server <- function(input, output) {

   PlotHeight = reactive(
      return( 500+250*(floor(input$plotcount/4)))
   )

   output$plots = renderPlot(height = PlotHeight(), {

      if( as.numeric(input$plotcount) == 0 ){
         plot.new()
         return()
      }
      print(c( floor(sqrt(as.numeric(input$plotcount))),
               ceiling(sqrt(as.numeric(input$plotcount)))
      ))
      opar = par( mfrow = c( floor(sqrt(as.numeric(input$plotcount))),
                             ceiling(sqrt(as.numeric(input$plotcount)))
                             )
                  )
      for( i in 1:as.numeric(input$plotcount) ){
         plot(1:100, 1:100, pch=19)
      }
      par(opar)
   })
}

shinyApp(ui =ui, server = server)

4
实际上,只需要将height = PlotHeight()替换为height = function() PlotHeight(),就可以使你的示例代码正常工作。 - Max
@Max,你能解释一下这是为什么/怎么工作的吗? - mihagazvoda
1
@mihagazvoda 请查看renderPlot的帮助页面-https://shiny.rstudio.com/reference/shiny/latest/renderPlot.html-在那里他们提到您需要提供一个函数,为了理解它的工作原理,请检查函数源代码-在那里您可以看到如果将函数提供为高度(或宽度),则会在`reactive()`包装器内执行。实际上,通过查看源代码,我意识到在这种情况下也可以提供`height = PlotHeight`,它也可以工作(但似乎未记录)。 - Max
1个回答

23

使用renderUI函数:

library(shiny)

ui <- fluidPage(
  fluidRow(
    column(
      width = 2
      , radioButtons(
          inputId = 'plotcount'
        , label   = 'Plot Count'
        , choices = as.character(1:4)
      )
    ),
    column(
      width = 10
      , uiOutput("plot.ui")
    )
  )
)

server <- function(input, output) {

  plotCount <- reactive({
    req(input$plotcount)
    as.numeric(input$plotcount)
  })

  plotHeight <- reactive(350 * plotCount())      

  output$plots <- renderPlot({

    req(plotCount())

    if (plotCount() == 0){
      plot.new()
      return()
    }

    opar <- par(mfrow = c(plotCount(), 1L))

    for (i in 1:plotCount()) {
      plot(1:100, 1:100, pch = 19)
    }

    par(opar)
  })

  output$plot.ui <- renderUI({
    plotOutput("plots", height = plotHeight())
  })

}

shinyApp(ui = ui, server = server)

太棒了!谢谢你! - KirkD-CO

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接