如何防止 selectizeInput 将空状态发送到闪亮?

问题描述 投票:0回答:1

我有一个闪亮的应用程序,其中有一个 selectizeInput。只有一个选择是有效的,但应该可以删除输入,以便可以开始输入以搜索所有选择。仅当用户选择了新选项时,才应通知shiny。如果用户没有选择新的选择(将 selectizeInput 留空并单击其他位置),则应恢复旧的未更改的选择。

我认为这种行为是很自然的。有没有办法实现这个目标?

这是一个应用程序,它展示了这如何有用:我总是想要一个带有标题的图,而不是没有标题的图:

library(shiny)
library(ggplot2)

ui <- fluidPage(
  selectizeInput("plottitle", "plot title", choices = letters, multiple=TRUE, options = list(maxItems = 1, minItems = 1)),
  plotOutput("po")
)

server <- function(input, output, session) {
  output$po <- renderPlot({
    ggplot(iris) + geom_point(aes(x=Sepal.Length, y=Sepal.Width)) + ggtitle(input$plottitle)
  })
}

shinyApp(ui, server)

请注意,minItems = 1 不起作用,也许我还可以做其他事情?

shiny selectize.js
1个回答
0
投票

这里的目标是防止 input$plottitle 为空时发生反应。为此,我仅在 input$plottitle 不为空时有条件地修改绘图,因此绘图永远不会没有标题。

唯一没有带有标题的情节的情况是在应用程序启动时:在用户选择标题之前根本没有情节。

library(shiny)
library(ggplot2)

ui <- fluidPage(
  selectizeInput("plottitle", "plot title", choices = letters, multiple=TRUE, options = list(maxItems = 1, minItems = 1)),
  plotOutput("po")
)

server <- function(input, output, session) {
  
  #Initialise a reactiveValues() to store the plot. (Note: you could also you a simple reactive())
  rv <- reactiveValues()
  
  # Fill rv$plot with the plot only if input$plottitle has a value
  observeEvent(input$plottitle, {
    rv$plot <- ggplot(iris) + geom_point(aes(x=Sepal.Length, y=Sepal.Width)) + ggtitle(input$plottitle)
  })
  
  #Finally, the plot
  output$po <- renderPlot({
    rv$plot
  })
}

shinyApp(ui, server)
© www.soinside.com 2019 - 2024. All rights reserved.