在 Shiny 中显示动态 UI 元素

阿卜杜勒阿赫德·本·哈梅德

我正在尝试在 Shiny 中生成动态图。绘图的数量事先不知道,所以我使用了 renderUI。问题是这些元素一个一个地显示在另一个之上。有没有办法指定按行显示的元素数量,然后一旦行被填充,代码就会传递到下一行?这是我简单的可重现示例:

library(shiny)

max_plots <- 50

server <- function(input, output) {
  
  output$plots <- renderUI({
    plot_and_radio_output_list <- lapply(1:input$n, function(i) {
      plotname <- paste("plot", i, sep="")
      list(
        plotOutput(plotname, height = 280, width = 250)
      )
    })
    do.call(tagList, unlist(plot_and_radio_output_list, recursive = FALSE))
  })
  
  for (i in 1:max_plots) {
    local({
      my_i <- i
      plotname <- paste("plot", my_i, sep="")
      output[[plotname]] <- renderPlot({
        plot(1:my_i, 1:my_i,
             xlim = c(1, max_plots),
             ylim = c(1, max_plots),
             main = paste("1:", my_i, ".  n is ", input$n, sep = "")
        )
      })
    })
  }
  
}

ui <- pageWithSidebar(
  
  headerPanel("Dynamic number of plots"),
  
  sidebarPanel(
    sliderInput("n", "Number of plots", value=1, min=1, max=5)
  ),
  
  mainPanel(
    uiOutput("plots")
  )
)

shinyApp(ui, server)
格德沃

你可以把你的图放在一个 div 中,并给它们 CSS 属性“inline-block”

  output$plots <- renderUI({
    plot_and_radio_output_list <- lapply(1:input$n, function(i) {
      plotname <- paste("plot", i, sep="")
      list(
        div(
          plotOutput(plotname, height = 280, width = 250),
          style = "display:inline-block;"
        )
        
      )
    })
    do.call(tagList, unlist(plot_and_radio_output_list, recursive = FALSE))
  })

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章