3

我想根据用户输入可视化绘图/秒。我有一个下拉菜单,如果用户从给定的选项中选择一个或多个变量,代码会根据用户输入自动可视化每个变量的单独图。

代码:这就是我尝试这样做的方式。如果有其他方法,请建议。

library(shiny)
library(shinyjs)

shinyApp(
  ui = fluidPage(
    useShinyjs(), #Necessary to activate shinyjs
    selectInput("select", "Select plot:", 1:4, multiple = TRUE),
    plotOutput("p1"),
    plotOutput("p2"),
    plotOutput("p3"),
    plotOutput("p4")
  ),
  server = function(input, output) {
    output$p1 <- renderPlot({ plot(iris) })
    output$p2 <- renderPlot({ plot(mtcars) })
    output$p3 <- renderPlot({ plot(0) })
    output$p4 <- renderPlot({ plot(1) })
    
    observeEvent(input$select, {
      req(input$select)
      shinyjs::toggle("p1", condition = input$select == 1)
      shinyjs::toggle("p2", condition = input$select == 2)
      shinyjs::toggle("p3", condition = input$select == 3)
      shinyjs::toggle("p4", condition = input$select == 4)
    })
    
  }
)

这段代码的问题是,当我从下拉菜单中选择任何一个输入时,其他变量的所有其他图也会显示出来。Plus when all the variables are selected and I try to unselect variable/s from the dropdown menu, they does not hide.

请帮忙。谢谢。

4

1 回答 1

2

As the selection allows multiple choice, you should use %in% instead of ==.
You should also use observe instead of observeEvent to react on NULL input.

library(shiny)
library(shinyjs)

shinyApp(
  ui = fluidPage(
    useShinyjs(), #Necessary to activate shinyjs
    selectizeInput("select", "Select plot:", 1:4, multiple = TRUE),
    plotOutput("p1"),
    plotOutput("p2"),
    plotOutput("p3"),
    plotOutput("p4")
  ),
  server = function(input, output) {
    output$p1 <- renderPlot({ plot(iris) })
    output$p2 <- renderPlot({ plot(mtcars) })
    output$p3 <- renderPlot({ plot(0) })
    output$p4 <- renderPlot({ plot(1) })

    observe({
      shinyjs::toggle("p1", condition = isTRUE(1 %in% input$select))
      shinyjs::toggle("p2", condition = isTRUE(2 %in% input$select))
      shinyjs::toggle("p3", condition = isTRUE(3 %in% input$select))
      shinyjs::toggle("p4", condition = isTRUE(4 %in% input$select))
    })
    
  }
)
于 2021-04-21T19:23:17.617 回答