制作闪亮的应用程序时,我经常会为如何在页面上为用户安排图表和文本输出而苦恼。因此,我想尝试使用户可以选择要显示的输出。例如,用户可能能够显示3个图和2个文本块,但可能只想显示第一个图和一个文本块。我通常可以使用呈现函数内部的if语句来完成此操作。但是,我发现即使...用户未指示应显示该图,发亮的仍将添加空白。这似乎是某种占位符空间,最终会在应用程序中留下很大的漏洞。在我的示例中,该应用程序显示了第二个图,但是有很大一部分空白使页面看起来很丑陋。
我发现了这一点:Shiny: unwanted space added by plotOutput() and/or renderPlot()并不完全适用。似乎没有针对这个特定问题的帖子。
library(shiny)
ui <- fluidPage(
titlePanel("Old Faithful Geyser Data"),
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)),
mainPanel(
plotOutput("distPlot"),
plotOutput("distPlot2"))))
server <- function(input, output) {
output$distPlot <- renderPlot({
if(input$bins == 4){
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = 'darkgray', border = 'white')
}})
output$distPlot2 <- renderPlot({
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = 'darkgray', border = 'white')})
}
shinyApp(ui = ui, server = server)
答案 0 :(得分:1)
在这种特殊情况下,两个可能的选择是将第一张图包装在shiny::conditionalPanel()
中,或者利用shiny::renderUI()
。
shiny::conditionalPanel()
示例
library(shiny)
ui <- fluidPage(
titlePanel("Old Faithful Geyser Data"),
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)),
mainPanel(
conditionalPanel("input.bins == 4", plotOutput("distPlot")),
plotOutput("distPlot2"))))
server <- function(input, output) {
output$distPlot <- renderPlot({
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
output$distPlot2 <- renderPlot({
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = 'darkgray', border = 'white')})
}
shinyApp(ui = ui, server = server)
shiny::renderUI()
示例
library(shiny)
ui <- fluidPage(
titlePanel("Old Faithful Geyser Data"),
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)),
mainPanel(
uiOutput("distPlots"))))
server <- function(input, output) {
output$distPlot <- renderPlot({
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
output$distPlot2 <- renderPlot({
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = 'darkgray', border = 'white')})
output$distPlots <- renderUI({
if(input$bins == 4)
fluidPage(plotOutput("distPlot"), plotOutput("distPlot2"))
else
plotOutput("distPlot2")
})
}
shinyApp(ui = ui, server = server)
两种方法都会产生此结果: