我正在玩shinyjs
pkg和隐藏/显示自定义UI的各种选项。在下面的应用程序中,我想显示选定的图表,如果未选择任何选项,则显示空白区域。我使用toggle()
,只要在checkboxGroupInput
中选择了至少一个选项就可以实现这一功能,但是如果没有选择任何选项,则会显示两个图。据documentation说:
如果给予切换条件,则该条件将用于确定是否显示或隐藏元素。如果条件的计算结果为TRUE,则会显示该元素,否则将隐藏该元素。
我错过了一些明显的东西吗?
library(shiny)
library(shinyjs)
library(ggplot2)
ui <-dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody(
useShinyjs(),
checkboxGroupInput(inputId = 'options',
label = 'Choose your plot(s)',
choices = list("Plot 1" = 1,
"Plot2" = 2)),
#selected = 1:2),
verbatimTextOutput('checkbox_text'),
uiOutput("Ui1"),
uiOutput('Ui2')
)
)
server <- function(input, output, session) {
output$checkbox_text <- renderText({
paste(input$options)
})
observe({
shinyjs::toggle(id = "Ui1", condition = input$options == 1)
shinyjs::toggle(id = "Ui2", condition = input$options == 2)
})
output$Ui1 <- renderUI({
output$plot1 <- renderPlot({
p <- ggplot(mtcars, aes(disp, mpg)) +
geom_point() +
geom_smooth() +
ggtitle('Plot 1')
p
})
plotOutput('plot1')
})
output$Ui2 <- renderUI({
output$plot2 <- renderPlot({
p<- ggplot(mtcars, aes(disp, mpg, colour = as.factor(cyl))) +
geom_point() +
ggtitle('Plot 2')
p
})
plotOutput('plot2')
})
}
shinyApp(ui, server)
当您在checkboxGroupInput
中查找哪些框时,通常最好对您感兴趣的值是否等于checkboxGroupInput
中的任何值进行评估 - 用此替换您的observe
语句将解决问题:
observe({
shinyjs::toggle(id = "Ui1", condition = {1 %in% input$options})
shinyjs::toggle(id = "Ui2", condition = {2 %in% input$options})
})
也就是说,我不确定为什么在你的情况下既没有盒子检查评估TRUE
。