金融科技选股机器人-shiny的使用教学-3

Shiny 的强大之处在于: 用户输入(input)发生变化 → 输出(output)会自动更新。 这就是 反应式编程 (Reactive Programming)

反应式输出函数

函数 用途
renderText() 输出文字
renderPlot() 输出图表
renderTable() 输出表格
renderPrint() 输出原始结果

配合 UI 端的输出函数:

  • textOutput()
  • plotOutput()
  • tableOutput()
  • verbatimTextOutput()

绘制直方图

我们做一个小应用:

  • 输入:选择要生成多少个随机数 (sliderInput)
  • 输出:绘制随机数的直方图 (renderPlot)
library(shiny)

ui <- fluidPage(
  titlePanel("Day 3: 随机数直方图"),

  sidebarLayout(
    sidebarPanel(
      sliderInput("num", "选择随机数个数:", 
                  min = 10, max = 1000, value = 100, step = 10)
    ),

    mainPanel(
      plotOutput("histPlot")
    )
  )
)

server <- function(input, output) {
  output$histPlot <- renderPlot({
    data <- rnorm(input$num)   # 生成随机数
    hist(data, 
         col = "skyblue", 
         border = "white",
         main = paste("直方图 -", input$num, "个随机数"),
         xlab = "数值")
  })
}

shinyApp(ui, server)

运行后你会看到:

  • 左边滑动条选择数量(10 ~ 1000)
  • 右边直方图会 自动更新

反应式表达式 reactive()

有时候需要在多个地方使用同一份计算结果,可以用 reactive()

例子:把随机数生成放在 reactive() 里:

server <- function(input, output) {
  rand_data <- reactive({
    rnorm(input$num)
  })

  output$histPlot <- renderPlot({
    hist(rand_data(), col = "orange", border = "white")
  })
}

这样 rand_data() 就是一个“动态变量”,可以在多个输出里复用。