如何在R Shiny的tab标签页中实现图表下方展示表格
问题修复方案
你遇到的问题由两个核心错误导致:
- 作用域错误:
names变量仅在renderPlotly的局部环境中定义,renderTable中调用时无法识别该变量,触发全局报错导致页面元素无法渲染 - 输出ID重复:Shiny不允许同一应用中存在重复的输出ID,若两个标签页都要展示表格,需要分别设置唯一的输出ID
修正后完整代码
library(shiny) library(plotly) library(ggplot2) # 请确保提前定义好以下全局变量:instability.data、channels、instability.summary、start、end、ii.threshold、control.mode ui <- fluidPage( titlePanel("Data"), sidebarLayout( sidebarPanel( selectInput(inputId = "sample_1", label = "Select sample 1:", choices = c(unique(instability.data$name))), selectInput(inputId = "sample_2", label = "Select sample 2:", choices = c(unique(instability.data$name))), selectInput(inputId = "target.channel", label = "Select channel:", choices = channels$name) ), mainPanel( tabsetPanel(type = "tabs", tabPanel("Target", plotlyOutput(outputId = "target"), tableOutput('table_target')), tabPanel("Full", plotlyOutput(outputId = "full"), tableOutput('table_full')) ) ) ) ) server <- function(input, output) { # 将选中的样本名封装为响应式变量,全局可用 selected_names <- reactive({ c(input$sample_1, input$sample_2) }) output$target <- renderPlotly({ names <- selected_names() d <- subset(instability.data, name %in% names & channel == input$target.channel & rpt>=start & rpt<=end) r <- ggplot(d, aes(x=rpt, y=rfu.rel, fill=name, colour=name)) + geom_line(size=0.1) + theme_bw() + geom_vline(aes(xintercept=start, colour=name), linetype="dotted") + geom_vline(aes(xintercept=end, colour=name), linetype="dotted") + geom_vline(aes(xintercept=control.mode, colour=name), linetype="dashed") + geom_hline(aes(yintercept=ii.threshold, colour=name), linetype="dotted") ggplotly(r) }) output$full <- renderPlotly({ names <- selected_names() d <- subset(instability.data, name %in% names & channel == input$target.channel) r <- ggplot(d, aes(x=rpt, y=rfu, fill=name, colour=name)) + geom_line(size=0.1) + theme_bw() + geom_vline(aes(xintercept=start, colour=name), linetype="dotted") + geom_vline(aes(xintercept=end, colour=name), linetype="dotted") + geom_vline(aes(xintercept=control.mode, colour=name), linetype="dashed") + geom_hline(aes(yintercept=ii.threshold, colour=name), linetype="dotted") ggplotly(r) }) # 两个标签页的表格分别渲染 output$table_target <- renderTable({ t <- subset(instability.summary, name %in% selected_names()) t[,-1] <- round(t[,-1], 2) t }) output$table_full <- renderTable({ t <- subset(instability.summary, name %in% selected_names()) t[,-1] <- round(t[,-1], 2) t }) } shinyApp(ui = ui, server = server)
界面效果

内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

