kto
kto

Reputation: 135

Setting a minimum range in a shiny app slider

When using a range slider in a shiny app, can you require a minimum range of selected values? I am using the sliderTextInput() function in the shinyWidgets package, but think this is general to range sliders. Toy example code:

testx=1:150
testy=1:150

library(shiny) # also requires shinyWidgets package be installed
ui <- fluidPage(

  plotOutput("plot"),
  shinyWidgets::sliderTextInput("range","Input Size:",
                                choices=c(1,25,50,100),
                                selected=c(25,50), grid = T)
)
server <- function(input, output) {
  output$plot <- renderPlot({
  plot(testx[input$range[1]:input$range[2]],testy[input$range[1]:input$range[2]],
             xlim=c(0,150),ylim=c(0,150))
      })
}
shinyApp(ui, server) 

The issue I am trying to avoid is the one below, where both ends of a slider are set to the same value, which results in a single point being plotted--I'd like to require a range be selected.

enter image description here

Upvotes: 0

Views: 800

Answers (1)

Pork Chop
Pork Chop

Reputation: 29387

You can update the values if the are the same:

testx=1:150
testy=1:150

library(shiny) # also requires shinyWidgets package be installed
library(shinyWidgets)

ui <- fluidPage(
  plotOutput("plot"),
  sliderTextInput("range","Input Size:",choices=sliderchoice,selected=c(25,50), grid = T)
)
server <- function(input, output,session) {

  observeEvent(input$range,{
    if(input$range[1] == input$range[2]){
      updateSliderTextInput(session,"range",selected = c((input$range[1]-1),input$range[2]))
    }
  })
  output$plot <- renderPlot({
    plot(testx[input$range[1]:input$range[2]],testy[input$range[1]:input$range[2]],
         xlim=c(0,150),ylim=c(0,150))
  })
}
shinyApp(ui, server) 

enter image description here

Upvotes: 1

Related Questions