如何使用 Shiny in R 中的滑块动态更新直方图的 x 轴范围

How to dynamically update the range of x-axis of histogram using sliders in Shiny in R

我见过用户使用 sliderInput 来调整直方图的 Bins 数量的示例。

但我的问题是如何使用 sliderInput 来调整 x 轴的范围而不是 Bins 的数量?我应该包括什么代码?

谁能帮帮我?我希望我的问题没有那么麻烦...

非常非常感谢。

这是一个基于可用 faithful 数据集的工作演示。我添加了一个 sliderInput 来调整 x 轴范围。 hist 包括 xlim 以定义 x 轴范围。注意第一个值是下限,第二个值是上限。

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)