You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R Shiny实现多直方图的交互式分箱数调整?

用R Shiny实现多组直方图的交互式分箱数调整

下面是实现多组直方图交互式分箱数调整的完整Shiny示例,以mtcars数据集为例:

library(shiny)
library(tidyverse)

ui <- fluidPage(
  titlePanel("多组直方图 - 交互式分箱调整"),
  sidebarLayout(
    sidebarPanel(
      # 分箱数调整滑块
      sliderInput("bins", "选择分箱数:",
                  min = 1, max = 50, value = 10)
    ),
    mainPanel(
      plotOutput("histPlot")
    )
  )
)

server <- function(input, output) {
  output$histPlot <- renderPlot({
    # 将宽格式数据转为长格式
    mtcars_long <- mtcars %>%
      gather(key = "变量", value = "数值")
    
    # 绘制多组直方图,分箱数绑定滑块输入
    ggplot(mtcars_long, aes(x = 数值)) +
      geom_histogram(bins = input$bins, fill = "#2c3e50", color = "white") +
      facet_wrap(~ 变量, scales = "free") +
      theme_bw() +
      labs(title = "多变量交互式直方图", x = "数值", y = "频数")
  })
}

shinyApp(ui = ui, server = server)

关键说明:

  • UI控件:通过sliderInput创建分箱数调节滑块,用户可以在1到50之间自由调整,默认值设为10
  • 数据整理:用gather把mtcars的宽格式数据转为长格式,让每个变量的数值都在同一列,方便分面绘制
  • 交互式绑定:在geom_histogram的bins参数中直接使用input$bins,实现滑块与分箱数的实时联动
  • 自适应分面:facet_wrap(~ 变量, scales = "free")让每个子图的坐标轴根据变量自身范围自动调整,避免数值差异大的变量展示失真

内容的提问来源于stack exchange,提问作者Russ Conte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 05:22:10