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

Shiny应用中如何存储上传表格并实现绘图功能?

Shiny Excel图表生成问题修复

问题根源

你的代码里有两个关键问题导致无法生成图表:

  • data响应式对象中读取Excel时,错误使用了input$datapath,正确路径应该是input$file1$datapath
  • 缺少针对plotOutput("OTD")的渲染逻辑,没有把响应式数据转化为图表

修正后的完整代码

library(shiny)
library(readxl)
library(dplyr)
library(tidyverse)
library(lubridate)

ui <- fluidPage(
  titlePanel("OTD project update"),
  sidebarPanel(
    fileInput('file1', 'Insert File', accept = c(".xlsx")),
    textInput('file1sheet','Name of Sheet (Case-Sensitive)')),
  mainPanel(tabsetPanel(
    type = "tabs",
    tabPanel("Data", tableOutput("value")),
    tabPanel("OTD", plotOutput("OTD"))        
    )   
  )
)

server <- function(input, output) {
    
  sheets_name <- reactive({
    if (!is.null(input$file1)) {
      return(excel_sheets(path = input$file1$datapath))  
    } else {
      return(NULL)
    }
  })
  
  # 响应式数据对象(修复路径错误)
  data <- reactive({
    if (!is.null(input$file1) && (input$file1sheet %in% sheets_name())) {
      read_excel(input$file1$datapath, sheet = input$file1sheet)
    } else {
      NULL
    }
  })
  
  # 数据表格渲染
  output$value <- renderTable({
    data()
  })
  
  # OTD图表渲染(示例逻辑,可根据你的数据结构调整)
  output$OTD <- renderPlot({
    req(data()) # 确保数据存在才执行绘图
    
    # 这里假设你的数据有date列和OTD列,可根据实际字段修改
    data() %>%
      mutate(date = ymd(date)) %>% # 确保日期格式正确
      ggplot(aes(x = date, y = OTD)) +
      geom_line(color = "blue") +
      labs(title = "OTD Trend", x = "Date", y = "OTD Value") +
      theme_minimal()
  })
}

shinyApp(ui, server)

关键说明

  • req(data())用于确保只有当响应式数据data()存在时,才执行绘图逻辑,避免空数据报错
  • 绘图部分的代码是示例,你需要根据自己Excel数据的实际字段名和需求调整(比如更换图表类型、修改映射变量等)
  • 把数据读取逻辑统一到data()响应式对象中,避免重复读取Excel,提升性能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 17:48:15