Shiny应用程序分为两个部分:用户界面定义和服务端脚本。
- 在教程的后续章节,我们将解释代码的细节并讲解如何用“反应性”表达式来生成输出。现在,就尝试运行一下例子程序,浏览一下源代码,以获得对shiny的初始印象。也请认真阅读注释。
library(shiny)
# Define UI for app that draws a histogram ----
ui <- fluidPage(
# App title ----
titlePanel("Hello Shiny!"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Slider for the number of bins ----
sliderInput(inputId = "bins",
label = "Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Histogram ----
plotOutput(outputId = "distPlot")
)
)
)
2.下面列出了服务端的代码。从某种程度上说,它很简单——生成给定个数的随机变量, 然后将直方图画出来。不过,你也注意到了,返回图形的函数被 renderPlot包裹着。函数上面的注释对此做出了一些解释,不过如果你觉得还是搞不明白,不用担心——后面我们将更进一步解释这个概念。
#定义绘制直方图所需的服务器逻辑
# Define server logic required to draw a histogram ----
server <- function(input, output) {
# Histogram of the Old Faithful Geyser Data ----
# with requested number of bins
# This expression that generates a histogram is wrapped in a call
# to renderPlot to indicate that:
# 1. It is "reactive" and therefore should be automatically
# re-executed when inputs (input$bins) change
它是“反应性的”,因此当输入(输入$bins)发生变化时应该是自动的 重新执行
# 2. Its output type is a plot
output$distPlot <- renderPlot({
x <- faithful$waiting
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = "#75AADB", border = "white",
xlab = "Waiting time to next eruption (in mins)",
main = "Histogram of waiting times")
})
}
3.创建shinyapp
# Create Shiny app ----
shinyApp(ui = ui, server = server)
网友评论