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

为什么这个简单的R Shiny代码无法用ggplot输出绘图?

问题原因

你代码存在两处直接导致绘图无法输出的错误:

  • 自定义interpol()函数仅定义了a、b两个入参,调用时额外传入的drop = FALSE属于多余参数,会触发参数不匹配报错
  • 绘图的美学映射中使用了Scenario字段,但你构造的数据集里并没有生成该列,会触发变量找不到的报错

修正后可运行的完整代码

library(ggplot2)
library(shiny)
library(shinyMatrix)
library(dplyr)

interpol <- function(a, b) { # a = 周期数, b = 矩阵输入
  c <- rep(NA, a)
  c[1] <- b[1]
  c[a] <- b[2]
  c <- approx(seq_along(c)[!is.na(c)], c[!is.na(c)], seq_along(c))$y # 插值逻辑
  return(c)
}

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      sliderInput('periods', '模拟周期数(X轴变量):', min=1, max=10, value=10),
      matrixInput("matrix1", 
                  label = "矩阵1:",
                  value = matrix(c(5), ncol = 1, dimnames = list("基准利率",NULL)),
                  cols =  list(names = FALSE),
                  class = "numeric"),
      matrixInput("matrix2",
                  label = "矩阵2(将和矩阵1关联):",
                  value = matrix(c(10,5), ncol = 2, dimnames = list(NULL,c("X","Y"))),
                  rows = list(extend = TRUE, delete = TRUE),
                  class = "numeric"),
    ),
    mainPanel(
      plotOutput("plot")
    )  
  )    
)

server <- function(input, output, session){
  plotData <- reactive({
    req(input$periods,input$matrix2)
    tryCatch(
      tibble(
        X = seq_len(input$periods),
        Y = interpol(input$periods,input$matrix2) # 移除多余的drop参数
      ),
      error = function(e) NULL
    )
  })
  
  output$plot <- renderPlot({
    req(plotData())
    plotData() %>% ggplot() + 
      geom_line(aes(x = X, y = Y), colour = "#0072B2") + # 移除不存在的Scenario映射,直接指定颜色
      theme(legend.title=element_blank())
  })
}

shinyApp(ui, server)

如果需要保留分组逻辑,你可以补充生成Scenario列的逻辑即可。

内容的提问来源于stack exchange,提问作者Curious Jorge - user9788072

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 06:54:07