【问题标题】:How can I change the layout reactively using input button in Shiny App?如何使用 Shiny App 中的输入按钮反应性地更改布局?
【发布时间】:2017-05-05 19:51:06
【问题描述】:

我正在尝试创建我的第一个 Shiny 应用程序,我基本上是在尝试让该应用程序绘制两个简单的直方图,但是通过输入按钮让用户选择是否要并排查看两个直方图(水平)或一个低于另一个(垂直)。

我尝试编写下面的代码更多是为了向您解释我的思维过程,而不是真正希望它会起作用。

感谢任何帮助,谢谢!

library(shiny)

ui <- fluidPage(
radioButtons('layout', 'Layout:', choices=c('Vertically', 'Horizontally'), inline=TRUE),
sliderInput(inputId = "num",
          label = "Choose a number",
          value = 25, min = 1, max = 100),
plotOutput("hist1"),
plotOutput("hist2"))

server <- function(input,output) {

if (input$layout == "Horizontally") {
  output$hist1<-fluidRow(
  column(3,plotOutput(hist(rnorm(input$num)))))
  output$hist2<-column(3,plotOutput(hist(rnorm(input$num))))
} 
else if (input$layout == "Vertically") {
  output$hist1<-fluidRow(
    column(3,plotOutput(hist(rnorm(input$num)))))
  output$hist2<-fluidRow(
    column(3,plotOutput(hist(rnorm(input$num)))))
}

}

shinyApp(ui=ui, server=server)

【问题讨论】:

    标签: shiny shinydashboard


    【解决方案1】:

    您可以使用renderUI 根据输入创建布局,并使用uiOutput 显示结果:

    ui <- fluidPage(
      radioButtons('layout', 'Layout:', choices=c('Vertically', 'Horizontally'), inline=TRUE),
      sliderInput(inputId = "num",
                  label = "Choose a number",
                  value = 25, min = 1, max = 100),
      uiOutput("plots"))
    
    server <- function(input,output) {
      output$hist1<-renderPlot(hist(rnorm(input$num)))
      output$hist2<-renderPlot(hist(rnorm(input$num)))
      output$plots<-renderUI(if (input$layout == "Horizontally") {
        fluidRow(column(3,plotOutput("hist1")),
                 column(3,plotOutput("hist2")))
        } 
        else if (input$layout == "Vertically") {
          fluidRow(plotOutput("hist1"),plotOutput("hist2"))
          })
    }
    
    shinyApp(ui=ui, server=server)
    

    【讨论】:

    • 太好了,谢谢!考虑到总是并排显示事物,如果我只想显示一个直方图或两者都显示,是否有办法通过输入按钮进行选择?
    • 是的,只需更改renderUI的内容以适应您的需要
    猜你喜欢
    • 2020-11-26
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 2021-11-08
    相关资源
    最近更新 更多