r语言 - 根据图形的数量以 "plotOutput" 的 Shiny 格式更改绘图区域的高度(自动)



我有一个"renderplot";在Shiny的服务器部分中产生1到4个数字的功能。我如何在闪亮的应用程序中根据数字的数量(自动)改变情节区域的高度?我的意思是4位数的高应该大于2位数的高。我用了ight = "auto", height = "auto"但出现了错误。所以我给它指定了一个固定的大小(height = "800"),但如果我有一个数字,它会非常大。如果有3个或4个,它们会变小。请查看我代码的一部分:

#UI section
plotOutput("fancyPlot",  inline = F, height = "800")
#Server section
output$fancyPlot <- renderPlot({
#I get the plot_list_final which has some plots (1 or 2 or 3 or 4).
n <-  lenght(plot_list_final )
nCol <- floor(sqrt(n))
p_last =  do.call("grid.arrange", c(plot_list_final, ncol=nCol))
return(p_last) 
})

您可以单独执行grid.arrange中的每个plot,例如在fluidPage中使用splitLayout。在这种情况下,每个图都有单独的图。在这种情况下,使用renderUI生成UI,以具有调整行数和列数的能力。

解决方案如下:

n <- 4 #(1 or 2 or 3 or 4)
nCol <- floor(sqrt(n))
nRow <- ceiling(n/nCol)
height <- "800"
ui <- fluidPage(
uiOutput("plotgrid")
)
server <- function(input, output, session) {
output$plotgrid <- renderUI({
lapply(1:nRow, function(k) {
do.call(splitLayout,
c(lapply(1:nCol,
function(l) {
plotOutput(paste("plot", k, l, sep = "-"), height = height)
})
)
)
})
})

observe({
lapply(1:nRow, function(k) {
lapply(1:nCol,
function(l) {
if (k*l <= n) {
output[[paste("plot", k, l, sep = "-")]] <- renderPlot({
# this is your plot
plot(rnorm(10), rnorm(10))
})
}
})
})
})

}
shinyApp(ui = ui, server = server)

最新更新