运行Shiny应用出现invalid 'width' or 'height'错误如何解决?
问题排查与解决
报错原因
- Shiny的
plotOutput组件默认使用固定高度值,renderPlot中定义的动态height参数要生效,必须先给对应plotOutput配置height = "auto",否则高度校验逻辑会判定动态返回值无效,抛出invalid 'width' or 'height'错误。 - 可选优化:可以给动态高度计算增加非空校验,避免页面初始加载时计算逻辑未完成返回空值引发的偶发报错。
修正后完整代码
library(ggplot2) library(shiny) library(tidyverse) mtcars$cyl = sample(letters[1:5], 32, TRUE) gg_facet_nrow<- function(p){ p %>% ggplot2::ggplot_build() %>% magrittr::extract2('layout') %>% magrittr::extract2('panel_layout') %>% magrittr::extract2('ROW') %>% unique() %>% length() } ui <- fluidPage( navbarPage(title="title", tabPanel("One", column(3, wellPanel( selectInput('name', 'NAME', c("A", "B")))), column(9, plotOutput('plot1', height = "auto"))) )) server <- function(input, output) { X <- reactive({input$name == "A"}) p1 <- reactive({ if(X()){ p1 <- ggplot(mtcars, aes(mpg, wt)) + facet_grid( . ~ gear ) }else{ p1 <- ggplot(mtcars, aes(mpg, wt)) + facet_grid( cyl ~ gear ) } return(p1) }) he <- reactive(gg_facet_nrow(p1())) output$plot1 <- renderPlot({p1() }, height = function(){req(he()); he()*300}) } shinyApp(ui,server)
内容的提问来源于stack exchange,提问作者QMan5
相关产品推荐
相关产品推荐

