R Shiny conditionalPanel下同一主面板无法渲染多图问题咨询
问题需求
现有默认编写的最小可复现示例(MWE)代码,首次启动App以及点击「Base rate」单选按钮时,仅会渲染plot1。需要实现如下效果:
- 首次启动App、点击「Base rate」单选按钮时,主面板同时渲染
plot1和plot2,两张图上下排列 - 点击「Spreads」单选按钮时保持现有逻辑,仅渲染
plot2
已尝试方案与排查情况
- 尝试修改
ui部分的conditionalPanel(condition = "input.tab2 == 'Base rate'",plotOutput("plot1")),,添加tagList(plotOutput("plot1"),plotOutput("plot2")),未成功 - 使用
fluidPage替代pageWithSidebar运行时,多图渲染功能正常,推测pageWithSidebar和/或conditionalPanel存在未明确的特性 - 明确不采用
renderUI方案:出于代码可读性和流程逻辑的考量,尽量避免使用renderUI
原始MWE代码
rm(list = ls()) library(shiny) rate1 <- matrix(c(1:20), 20, 1, dimnames = list(NULL,c("Base rate"))) rate2 <- matrix(c(21:40), 20, 1, dimnames = list(NULL,c("Spreads"))) ui <- pageWithSidebar( headerPanel("Model"), sidebarPanel(), mainPanel( tabsetPanel( tabPanel("Rates", value=2, fluidRow( radioButtons( inputId = 'tab2', label = "", choices = c('Base rate','Spreads'), selected = 'Base rate', inline = TRUE ) ), conditionalPanel(condition = "input.tab2 == 'Base rate'",plotOutput("plot1")), conditionalPanel(condition = "input.tab2 == 'Spreads'", plotOutput("plot2")), ), id = "tabselected" ) ) ) server <- function(input,output,session)({ output$plot1 <-renderPlot({plot(rate1)}) output$plot2 <-renderPlot({plot(rate2)}) }) # close server shinyApp(ui, server)
修正后MWE代码
修正基于两点规则:
- 同一绘图输出不能在UI中重复调用
pageWithSidebar已弃用,替换为fluidPage+sidebarLayout组合
rm(list = ls()) library(shiny) rate1 <- matrix(c(1:20), 20, 1, dimnames = list(NULL,c("Base rate"))) rate2 <- matrix(c(21:40), 20, 1, dimnames = list(NULL,c("Spreads"))) ui <- fluidPage( titlePanel("Model"), sidebarLayout( sidebarPanel(), mainPanel( tabsetPanel( tabPanel("Rates", value=2, fluidRow( radioButtons( inputId = 'tab2', label = "", choices = c('Base rate','Spreads'), selected = 'Base rate', inline = TRUE ) ), conditionalPanel(condition = "input.tab2 == 'Base rate'",plotOutput("plot1"),plotOutput("plot2")), conditionalPanel(condition = "input.tab2 == 'Spreads'",plotOutput("plot3")), ), id = "tabselected" ) ) ) ) server <- function(input, output) { output$plot1 <-renderPlot({plot(rate1)}) output$plot2 <-renderPlot({plot(rate2)}) output$plot3 <-renderPlot({plot(rate2)}) } shinyApp(ui, server)
内容的提问来源于stack exchange,提问作者Curious Jorge - user9788072
相关产品推荐
相关产品推荐

