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

新手求助:修复展示多支股票数据的R Shiny应用问题

修复你的R Shiny股票数据展示应用

原代码存在的问题

  • Server逻辑仅处理了Amazon股票,切换到Apple/Tesla时无响应
  • 使用了已弃用的aes_string()函数,易引发兼容性问题
  • 重复加载shiny库,冗余且无必要
  • 未实现你需求的数据表格展示功能
  • 未使用反应式表达式,代码复用性差

修复后的完整代码

首先确保安装所需依赖包:

install.packages(c("shiny", "tidyverse", "tidyquant", "plotly", "colourpicker"))

然后运行以下代码:

# 加载依赖库
library(shiny)
library(tidyverse)
library(tidyquant)
library(plotly)
library(colourpicker)

# 批量获取并整理股票数据,用列表存储更高效
stock_data <- list(
  "Amazon" = tq_get("AMZN", get = "stock.prices", from = "2022-01-01", to = "2022-08-30"),
  "Apple" = tq_get("AAPL", get = "stock.prices", from = "2022-01-01", to = "2022-08-30"),
  "Tesla" = tq_get("TSLA", get = "stock.prices", from = "2022-01-01", to = "2022-08-30")
)

ui <- fluidPage(
  titlePanel("股票数据展示"),
  verticalLayout(
    # 股票选择按钮
    radioButtons(
      inputId = "accion",
      label = "选择要查看的股票",
      choices = names(stock_data),
      selected = "Amazon",
      inline = TRUE
    ),
    # Y轴变量选择按钮
    radioButtons(
      inputId = "var_y",
      label = "选择要展示的指标",
      choices = c("收盘价" = "close", "开盘价" = "open", "成交量" = "volume"),
      selected = "close",
      inline = TRUE
    ),
    # 颜色选择器
    colourInput(
      inputId = "col",
      label = "选择线条颜色",
      value = "black"
    ),
    # 图表输出
    plotlyOutput(outputId = "grafica"),
    # 表格输出(新增)
    h3("详细数据表格"),
    tableOutput(outputId = "stock_table")
  )
)

server <- function(input, output, session) {
  # 反应式获取选中的股票数据,避免重复代码
  selected_data <- reactive({
    stock_data[[input$accion]]
  })

  # 渲染交互式图表
  output$grafica <- renderPlotly({
    ggplot(selected_data(), aes(x = date)) +
      # 使用.data代词引用动态变量,替代已弃用的aes_string
      geom_line(aes(y = .data[[input$var_y]]), color = input$col) +
      # 动态设置Y轴标题
      labs(y = switch(input$var_y, 
                     "close" = "收盘价", 
                     "open" = "开盘价", 
                     "volume" = "成交量"),
           x = "日期") +
      theme_minimal()
  })

  # 渲染数据表格(新增)
  output$stock_table <- renderTable({
    selected_data() %>%
      select(date, open, high, low, close, volume) %>%
      # 数值保留两位小数,提升可读性
      mutate(across(where(is.numeric), ~round(., 2)))
  })
}

shinyApp(ui, server)

关键修改说明

  1. 数据结构优化:将三只股票数据存入列表,通过选择器直接调用,避免冗余的条件判断
  2. 弃用函数替换:用.data[[input$var_y]]替代aes_string(),符合tidyverse最新规范
  3. 反应式编程:用reactive()定义selected_data,所有依赖该数据的输出会自动更新
  4. 新增表格功能:添加tableOutput和对应的渲染逻辑,展示完整股票数据
  5. UI优化:将指标选项改为中文,提升易用性;动态设置图表Y轴标题,展示更清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:21:28