【问题标题】:Display table or chart in the same box upon clicking different buttons in R shiny单击 R Shiny 中的不同按钮后,在同一框中显示表格或图表
【发布时间】:2021-05-24 01:40:18
【问题描述】:

我正在尝试创建一个带有 2 个按钮的应用程序,以在同一框内容中显示图表或表格(不是两者)。 例如,如果用户点击图表按钮,图表就会出现。同样点击表格按钮,表格出现在同一个地方,图表消失。

小例子

if (interactive()) {
  library(shiny)
  library(shinydashboard)
  shinyApp(
    ui = shinydashboard::dashboardPage(
      header = dashboardHeader(),
      sidebar = dashboardSidebar(),
      body = dashboardBody(
        actionButton(inputId = 'input1', label = 'Chart'),
        actionButton(inputId = 'input2', label = 'Table'),
        box(
          uiOutput('plot_table_output'))
      ),
      title = "DashboardPage"
    ),
    server = function(input, output) {
      output$plot_table_output <- renderUI({
        if(input$input1 >0) {
          plotOutput('my_plot')
        }
        if(input$input2 >0) {
          dataTableOutput('mytable')
        } 
      })
      
      output$my_plot <- renderPlot({
        mydf <- data.frame(X=1:10, Y=1:10)
        plot(mydf$X, mydf$Y, type = 'l')
      })
      
      output$mytable <- renderDataTable({
        mydf <-  data.frame(X=1:10, Y=1:10)
        mydf
      })   
    }
  )
}

【问题讨论】:

    标签: r shiny action-button


    【解决方案1】:

    一种方法是使用ObserveEvent()。试试这个

    library(shiny)
    library(shinydashboard)
    shinyApp(
      ui = shinydashboard::dashboardPage(
        header = dashboardHeader(),
        sidebar = dashboardSidebar(),
        body = dashboardBody(
          actionButton(inputId = 'input1', label = 'Chart'),
          actionButton(inputId = 'input2', label = 'Table'),
          box(
            uiOutput('plot_table_output'))
        ),
        title = "DashboardPage"
      ),
      server = function(input, output) {
        
        observeEvent(input$input1, {
          output$plot_table_output <- renderUI({
              plotOutput('my_plot')
          })
        })
        
        observeEvent(input$input2, {
          output$plot_table_output <- renderUI({
            dataTableOutput('mytable')
          })
        })
        
        output$my_plot <- renderPlot({
          mydf <- data.frame(X=1:10, Y=1:10)
          plot(mydf$X, mydf$Y, type = 'l')
        })
        
        output$mytable <- renderDataTable({
          mydf <-  data.frame(X=1:10, Y=1:10)
          mydf
        })   
      }
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多