Shiny中为Plotly绘图加box报错:plot.new has not been called yet求助
问题解决:Shiny中添加box包裹Plotly输出报错的问题
错误原因
你调用的box()是R基础绘图系统的函数(用于给base R绘制的图形添加边框),并非Shiny UI的布局组件。在Shiny UI环境中调用这个函数,会触发基础绘图的错误提示plot.new has not been called yet,因为它找不到对应的基础绘图上下文。
解决方案
要在Shiny中实现带边框的容器包裹Plotly输出,需要使用shinydashboard包提供的box()组件,这是专门为Shiny UI布局设计的组件。
步骤1:安装并加载shinydashboard包
install.packages("shinydashboard") # 首次使用需执行安装 library(shiny) library(plotly) library(ggplot2) library(shinydashboard) # 加载布局组件包 source("simulated_annealing.R")
步骤2:修正UI代码
直接用shinydashboard::box()(加载包后可直接写box())包裹plotlyOutput即可:
ui <- fluidPage( titlePanel("Simulated Annealing App"), mainPanel( strong("SYSTEM OUTPUTS"), box(plotlyOutput("tempplot"), width = 12) # width参数可按需调整容器宽度 ) )
额外提示:服务器端代码优化
原服务器代码存在两处小问题,建议同步修正:
- 条件判断
as.numeric(input$maxormin == 2)的括号位置错误,应改为as.numeric(input$maxormin) == 2 simannealing函数中用alpha <- as.double(input$ALPHA)的赋值方式不符合参数传递规范,应改为alpha = as.double(input$ALPHA)- 列表索引
value[4]改为value[[4]]更稳妥,避免返回子列表而非向量
修正后的服务器代码:
server <- function(input, output) { observeEvent(input$Go, { Func <- as.character(input$ObjectiveFun) if(as.numeric(input$maxormin) == 2) { Func <- paste("-(", Func, ")", sep = "", collapse = "") } value <- simannealing( Func, as.numeric(input$TEMP), as.numeric(input$NITER), as.numeric(input$AMIN), alpha = as.double(input$ALPHA), as.numeric(input$NEPOCHS), as.numeric(input$XL), as.numeric(input$XU), as.numeric(input$YL), as.numeric(input$YU) ) tempdata <- data.frame(x = 1:length(value[[4]]), y = value[[4]]) output$tempplot <- renderPlotly({ plot_ly(tempdata, x = ~x, y = ~y, type = "scatter", mode = "markers", marker = list(size = 5, color = "red")) %>% layout(title = "Temperature change", xaxis = list(title = "Number of iterations"), yaxis = list(title = "Temperature")) }) }) } shinyApp(ui = ui, server = server)
内容的提问来源于stack exchange,提问作者shongololo
相关产品推荐
相关产品推荐

