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

在RShiny中使用box函数为何出现‘plot.new has not been called yet’错误?

问题原因

你触发的错误是因为误用了base R里的box()函数——这个函数是给已绘制的图形加边框用的,必须在绘图操作(比如plot())之后调用,在Shiny UI的布局代码里直接调用自然会报错。你真正需要的是用于页面布局的box()组件,这个组件属于shinydashboard包,不是Shiny原生自带的。

另外原代码还有个小问题:mainPanel里直接嵌套tabPanel是无效的,子标签页得用tabsetPanel包裹才能正常显示。

修复步骤
  1. 先安装并加载shinydashboard包
  2. 修正box()的调用方式,同时调整标签页的嵌套结构
修复后的完整代码
library(shiny)
library(shinydashboard)

# USER INTERFACE ####
ui <-  fluidPage(
  navbarPage(
    "主页面",
    tabPanel(
      "TAB1",   
      mainPanel(
        tabsetPanel(
          tabPanel(
            "Subtab1",
            fluidRow(
              "TEF",
              column(
                12, 
                box(width = 6, title = "CE", plotOutput("plot1")),
                box(width = 6, title = "CO", plotOutput("plot2"))
              )
            )
          )
        )
      )
    )
  )
)

# SERVER ####
server <- function(input, output, session) {
  output$plot1 <- renderPlot(plot(mtcars$mpg, mtcars$cyl))
  output$plot2 <- renderPlot(plot(mtcars$mpg, mtcars$gear))
}

shinyApp(ui = ui, server = server)
替代方案(不用shinydashboard)

如果不想额外加载包,也可以用Shiny原生的wellPanel实现类似盒子布局:

library(shiny)

# USER INTERFACE ####
ui <-  fluidPage(
  navbarPage(
    "主页面",
    tabPanel(
      "TAB1",   
      mainPanel(
        tabsetPanel(
          tabPanel(
            "Subtab1",
            fluidRow(
              "TEF",
              column(
                12, 
                wellPanel(style = "width: 50%; float: left;", 
                          h4("CE"), plotOutput("plot1")),
                wellPanel(style = "width: 50%; float: left;", 
                          h4("CO"), plotOutput("plot2"))
              )
            )
          )
        )
      )
    )
  )
)

# SERVER ####
server <- function(input, output, session) {
  output$plot1 <- renderPlot(plot(mtcars$mpg, mtcars$cyl))
  output$plot2 <- renderPlot(plot(mtcars$mpg, mtcars$gear))
}

shinyApp(ui = ui, server = server)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 08:01:57