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

如何在R Shiny中自定义布局实现表格与图表水平对齐?

Shiny布局:实现gt表格与ggplot水平排列

下面提供两种简单高效的方案,基于模拟数据场景调整布局:

方案1:使用fluidRow + column(栅格布局,推荐)

这是Shiny官方推荐的布局方式,通过12列栅格系统灵活控制组件宽度比例:

library(shiny)
library(ggplot2)
library(gt)

ui <- fluidPage(
  titlePanel("示例应用"),
  mainPanel(
    # 用fluidRow包裹,内部分两个column实现水平排列
    fluidRow(
      # 表格占6列,图表占6列(总12列,可按需调整比例)
      column(width = 6, gt_output("table")),
      column(width = 6, plotOutput("plot"))
    )
  )
)

server <- function(input, output) {
  sim_data <- reactive({
    data.frame(
      类别 = LETTERS[1:5],
      数值1 = rnorm(5, 10, 2),
      数值2 = rnorm(5, 20, 3)
    )
  })
  
  output$table <- render_gt({
    sim_data() %>%
      gt() %>%
      tab_header(title = "模拟数据表格")
  })
  
  output$plot <- renderPlot({
    ggplot(sim_data(), aes(x = 类别, y = 数值1, fill = 类别)) +
      geom_col() +
      labs(title = "数值1柱状图") +
      theme_minimal()
  })
}

shinyApp(ui, server)

调整技巧

  • 可修改column的width参数调整占比(比如表格4列、图表8列,总和保持12即可)
  • 若表格内容过长,可添加滚动条:
    column(width = 6, gt_output("table"), style = "overflow-y: auto; max-height: 500px;")
    

方案2:使用splitLayout(快速水平分割)

适合需要快速实现等分或固定宽度的场景:

library(shiny)
library(ggplot2)
library(gt)

ui <- fluidPage(
  titlePanel("示例应用"),
  mainPanel(
    # splitLayout自动水平排列组件,cellWidths指定宽度比例
    splitLayout(
      cellWidths = c("50%", "50%"), # 支持百分比、像素(如"400px")
      gt_output("table"),
      plotOutput("plot")
    )
  )
)

server <- function(input, output) {
  sim_data <- reactive({
    data.frame(
      类别 = LETTERS[1:5],
      数值1 = rnorm(5, 10, 2),
      数值2 = rnorm(5, 20, 3)
    )
  })
  
  output$table <- render_gt({
    sim_data() %>%
      gt() %>%
      tab_header(title = "模拟数据表格")
  })
  
  output$plot <- renderPlot({
    ggplot(sim_data(), aes(x = 类别, y = 数值1, fill = 类别)) +
      geom_col() +
      labs(title = "数值1柱状图") +
      theme_minimal()
  })
}

shinyApp(ui, server)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 17:52:48