1

I have seen examples that user use sliderInput to adjust the number of Bins of the histogram.

But my question is how can I use the sliderInput to adjust the range of the x-axis instead of number of Bins? What code should I include?

Can anyone help me? I hope my question is not that troubling...

Thank you very very much.

Conor Neilson
  • 1,026
  • 1
  • 11
  • 27
Gambit
  • 77
  • 1
  • 11

1 Answers1

2

Here is a working demo based on the available faithful dataset. I added a sliderInput to adjust the x-axis range. The hist includes xlim to define the x-axis range. Note the first value is the lower limit, and the second value is the upper limit.

library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      sliderInput("bins",
                  "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30),
      sliderInput("x_range", "Range:",
                  min = 0, max = 100, value = c(0, 100), step = 10)
    ),
    mainPanel(
      plotOutput("distPlot")
    )
  )
)

server <- function(input, output, session) {
  output$distPlot <- renderPlot({
    x    <- faithful[, 2]  # Old Faithful Geyser data
    bins <- seq(min(x), max(x), length.out = input$bins + 1)
    hist(x, breaks = bins, xlim = c(input$x_range[1], input$x_range[2]), col = 'darkgray', border = 'white')
  })
}

shinyApp(ui, server)
Ben
  • 28,684
  • 5
  • 23
  • 45
  • Thank you very much! It really helps, really really very appreciate it – Gambit Apr 04 '20 at 16:48
  • Is there a solution for when the range of the variable is not known in advance and we want the default range to be min to max of that variable? – papgeo Oct 14 '22 at 21:50
  • @papgeo Yes, you can dynamically create the `sliderInput` in your `server` function, such as in [this answer](https://stackoverflow.com/a/24114892/3460670) - is that what you had in mind? Or you can try using `updateSliderInput` with the range based on a variable available in `server`... – Ben Oct 15 '22 at 01:03
  • @Ben Thank you Ben. updateSliderInput has worked for me. – papgeo Oct 15 '22 at 07:38