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

运行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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:48:02