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

Shiny中renderTable/Plot与renderDT宽度适配及fasta序列并排问题

解决Shiny中renderPlot/序列并排与宽度适配问题

核心解决方案代码

以下是修改后的示例代码,直接解决两个fasta序列并排不重叠、plot占满100%宽度的问题:

library(shiny)
library(DT)
library(ggplot2)

ui <- fluidPage(
  # 自定义样式适配布局与宽度
  tags$style(HTML("
    .fasta-box {
      width: 48%;
      display: inline-block;
      vertical-align: top;
      margin-right: 1%;
      white-space: pre-wrap;
      word-break: break-all;
    }
    .full-width-plot {
      width: 100%;
      margin-top: 20px;
    }
  ")),
  
  # 并排显示两个FASTA序列
  fluidRow(
    div(class = "fasta-box",
        h4("序列1"),
        verbatimTextOutput("fasta1")
    ),
    div(class = "fasta-box",
        h4("序列2"),
        verbatimTextOutput("fasta2")
    )
  ),
  
  # 占满100%宽度的绘图
  div(class = "full-width-plot",
      plotOutput("wide_plot", width = "100%")
  ),
  
  # 对比用的DT表格
  DTOutput("wide_dt")
)

server <- function(input, output) {
  # 生成示例FASTA序列
  output$fasta1 <- renderPrint({
    cat(">Seq1\n", paste(sample(c("A", "T", "C", "G"), 200, replace = TRUE), collapse = ""))
  })
  
  output$fasta2 <- renderPrint({
    cat(">Seq2\n", paste(sample(c("A", "T", "C", "G"), 200, replace = TRUE), collapse = ""))
  })
  
  # 生成占满宽度的绘图
  output$wide_plot <- renderPlot({
    ggplot(mtcars, aes(x = wt, y = mpg)) + 
      geom_point() +
      theme(plot.width = unit(1, "npc"))
  }, width = "100%")
  
  # 生成宽DT表格
  output$wide_dt <- renderDT({
    wide_df <- as.data.frame(matrix(rnorm(10*20), nrow = 10))
    datatable(wide_df, options = list(scrollX = TRUE))
  })
}

shinyApp(ui, server)

关键改动说明

  • FASTA序列并排:

    • 自定义.fasta-box样式,用display: inline-block和width: 48%让两个容器各占近一半宽度,vertical-align: top保证顶部对齐
    • 添加white-space: pre-wrap和word-break: break-all,避免长序列溢出导致重叠
    • 用div包裹序列输出,应用自定义样式
  • Plot占满100%宽度:

    • 在plotOutput中设置width = "100%",让输出容器占满父元素宽度
    • 在renderPlot中设置width = "100%",确保绘图内容自适应容器
    • 用theme(plot.width = unit(1, "npc"))强制ggplot内部布局占满可用空间
  • 突破Bootstrap 12列限制:

    • 避免将plot或序列容器嵌套在column()中(默认受12列栅格限制),直接用fluidRow+自定义div布局
    • DT的scrollX = TRUE选项实现表格横向滚动,配合全宽容器突破宽度限制

简化替代方案

如果不想写自定义CSS,可用Shiny原生splitLayout实现序列并排:

splitLayout(cellWidths = c("50%", "50%"),
            verbatimTextOutput("fasta1"),
            verbatimTextOutput("fasta2")
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 14:01:01