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

调整R Shiny代码实现按所选日期和类别正确渲染对应图形

解决方案

核心修改点

  • 删除原function.test内部硬编码的固定参数赋值行,保留传入参数的有效性
  • 重构逻辑拆分:将数据集定义、下拉选项生成、绘图逻辑分离,避免重复计算
  • 修正绘图逻辑调用方式:基础绘图不需要捕获返回值,直接在renderPlot中执行即可生成动态图形
  • 兼容两种测试数据集,直接替换代码中的df1定义即可验证兼容性

完整可运行代码

library(shiny)
library(shinythemes)
library(dplyr)
library(tidyverse)
library(lubridate)
library(stringr)

# 可直接替换为5行测试数据集验证兼容性
df1 <- structure(
  list(date1= c("2021-06-28","2021-06-28","2021-06-28","2021-06-28"),
       date2 = c("2021-06-30","2021-06-30","2021-07-01","2021-07-01"),
       Category = c("FDE","ABC","FDE","ABC"),
       Week= c("Wednesday","Wednesday","Friday","Friday"),
       DR1 = c(4,1,6,3),
       DR01 = c(4,1,4,3), DR02= c(4,2,6,2),DR03= c(9,5,4,7),
       DR04 = c(5,4,3,2),DR05 = c(5,4,5,4),
       DR06 = c(2,4,3,2),DR07 = c(2,5,4,4),
       DR08 = c(3,4,5,4),DR09 = c(2,3,4,4)),
  class = "data.frame", row.names = c(NA, -4L))

# 绘图函数独立定义
f1 <- function(dmda, CategoryChosse) {
  x<-df1 %>% select(starts_with("DR0"))
  
  x<-cbind(df1, setNames(df1$DR1 - x, paste0(names(x), "_PV")))
  PV<-select(x, date2,Week, Category, DR1, ends_with("PV"))
  
  med<-PV %>%
    group_by(Category,Week) %>%
    summarize(across(ends_with("PV"), median), .groups = "drop")
  
  SPV<-df1 %>%
    inner_join(med, by = c('Category', 'Week')) %>%
    mutate(across(matches("^DR0\\d+$"), ~.x + 
                    get(paste0(cur_column(), '_PV')),
                  .names = '{col}_{col}_PV')) %>%
    select(date1:Category, DR01_DR01_PV:last_col())
  
  SPV<-data.frame(SPV)
  
  mat1 <- df1 %>%
    filter(date2 == dmda, Category == CategoryChosse) %>%
    select(starts_with("DR0")) %>%
    pivot_longer(cols = everything()) %>%
    arrange(desc(row_number())) %>%
    mutate(cs = cumsum(value)) %>%
    filter(cs == 0) %>%
    pull(name)
  
  dropnames <- paste0(mat1,"_",mat1, "_PV")
  
  SPV <- SPV %>%
    filter(date2 == dmda, Category == CategoryChosse) %>%
    select(-any_of(dropnames))
  
  datas<-SPV %>%
    filter(date2 == ymd(dmda)) %>%
    group_by(Category) %>%
    summarize(across(starts_with("DR0"), sum), .groups = "drop") %>%
    pivot_longer(cols= -Category, names_pattern = "DR0(.+)", values_to = "val") %>%
    mutate(name = readr::parse_number(name))
  colnames(datas)[-1]<-c("Days","Numbers")
  
  datas <- datas %>% 
    group_by(Category) %>% 
    slice((as.Date(dmda) - min(as.Date(df1$date1) [
      df1$Category == first(Category)])):max(Days)+1) %>%
    ungroup
  
  plot(Numbers ~ Days,  xlim= c(0,45), ylim= c(0,30),
       xaxs='i',data = datas,main = paste0(dmda, "-", CategoryChosse))
  
  model <- nls(Numbers ~ b1*Days^2+b2,start = list(b1 = 0,b2 = 0),data = datas, algorithm = "port")
  
  new.data <- data.frame(Days = with(datas, seq(min(Days),max(Days),len = 45)))
  new.data <- rbind(0, new.data)
  lines(new.data$Days,predict(model,newdata = new.data),lwd=2)
  coef<-coef(model)[2]
  points(0, coef, col="red",pch=19,cex = 2,xpd=TRUE)
  text(.99,coef + 1,max(0, round(coef,1)), cex=1.1,pos=4,offset =1,col="black")
}

ui <- fluidPage(
  shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
                    br(),
                    tabPanel("",
                             sidebarLayout(
                               sidebarPanel(
                                 uiOutput("date"),
                                 uiOutput("mycode"),
                                 br()
                               ),
                               mainPanel(
                                 tabsetPanel(
                                   tabPanel("", plotOutput("graph",width = "100%", height = "600") 
                                   )
                                 )
                               ))
                    )))

server <- function(input, output,session) {
  # 全局可用的日期选项
  available_dates <- unique(df1$date2)
  
  output$date <- renderUI({
    all_dates <- seq(as.Date(min(df1$date2))-30, as.Date(max(df1$date2))+30, by = "day")
    disabled <- as.Date(setdiff(all_dates, as.Date(available_dates)), origin = "1970-01-01")
    dateInput(input = "date2", 
              label = h4("Data"),
              min = min(as.Date(available_dates)),
              max = max(as.Date(available_dates)),
              value = min(as.Date(available_dates)),
              format = "dd-mm-yyyy",
              datesdisabled = disabled)
  })
  
  output$mycode <- renderUI({
    req(input$date2)
    filtered_cats <- unique(df1$Category[as.Date(df1$date2) %in% as.Date(input$date2)])
    selectInput("code", label = h4("Code"),choices=filtered_cats)
  })
  
  output$graph <- renderPlot({
    req(input$date2,input$code)
    f1(as.character(input$date2), as.character(input$code))
  })
}

shinyApp(ui = ui, server = server)

兼容性验证说明

如果需要使用5行测试数据集,直接替换代码中df1的定义部分即可,其余逻辑不需要修改,可直接正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:57:03