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

RShiny中通过下拉菜单选择绘图出现报错该如何修复

问题修复方案

代码错误点

  • switch分支拼写错误:两个分支都绑定了"Plot-1",导致选择Plot-2时没有匹配项返回NULL
  • 变量作用域错误:Plot1/Plot2是在renderPlot函数内部定义的,外层的eventReactive完全无法访问这两个变量
  • 逻辑结构错误:eventReactive没有返回正确的绘图对象,renderPlot也没有输出选中的绘图
  • 冗余代码:navbarPage下的uiOutput("all")没有对应输出逻辑,会额外生成一个空白标签页

修复后完整代码

library(shiny)
library(shinydashboard)
library(shinythemes) 
library(tidyverse)

# UI端
ui =   navbarPage("Project ", theme = shinytheme("cyborg"),
                  tabPanel("Plot",
                           icon = icon("chart-area"),
                           sidebarLayout(sidebarPanel(
                             selectInput("Plot", "请选择要查看的绘图:",
                                         choices = c("Plot-1", "Plot-2")),
                             submitButton("提交")),
                             plotOutput(outputId = "Plots",
                                        width = "1024px",
                                        height = "768px")
                           )))

# Server端
server = function(input, output, session) {
  # 示例数据仅需加载一次
  data("midwest", package = "ggplot2")
  
  output$Plots = renderPlot({
    # 定义绘图对象
    Plot1 = ggplot(midwest, aes(x=area, y=poptotal)) +
      geom_point()
    Plot2 =  ggplot(midwest, aes(x=area, y=poptotal)) + geom_point() + 
      geom_smooth(method="lm")
    # 根据用户选择返回对应绘图
    switch(input$Plot,
           "Plot-1" = Plot1,
           "Plot-2" = Plot2)
  })
}

# 运行应用
shinyApp(ui = ui, server = server)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:06:03