Shiny是一个能方便构建交互式网页应用的R包,出自Rsutio,在官网中有非常多的学习资料。有视频和文字教程,也有基础和进阶,更难得的是有其他开发者发布的产品,值得学习。
这里是shiny基础系列,旨在对shiny基本用法有所了解。当然重复语法不过多解释,更多记录下注意事项。
- Lesson 1 - Welcome to Shiny
- Lesson 2 - Layout the user interface
- Lesson 3 - Add control widgets
- Lesson 4 - Display reactive output
- Lesson 5 - Use R scripts and data
- Lesson 6 - Use reactive expressions
- Lesson 7 - Share your apps
内置示例
shiny包有11个内置示例,基本覆盖了Shiny的工作方式,可以在Rstudio中一一运行,结合代码学习:
library(shiny)
runExample("01_hello") # a histogram
runExample("02_text") # tables and data frames
runExample("03_reactivity") # a reactive expression
runExample("04_mpg") # global variables
runExample("05_sliders") # slider bars
runExample("06_tabsets") # tabbed panels
runExample("07_widgets") # help text and submit buttons
runExample("08_html") # Shiny app built from HTML
runExample("09_upload") # file upload wizard
runExample("10_download") # file download wizard
runExample("11_timer") # an automated timer
shiny结构与运行
三部分结构:
- ui:定义用户界面
- server:构建应用程序
- shinyApp函数:调用应用程序
运行方式:
- 三部分结构可放在一个脚本中(如
app.R
),直接运行脚本即可,方便共享代码; - 创建
app
的目录(如my_app
),ui.R
和server.R
分别放在其中,在外部运行shiny::runAPP("my_app")
。
示例如下:
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")
)
)
)
# 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
# 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")
})
}
shinyApp(ui = ui, server = server)
runAPP("my_app")
默认正常模式展示,即没有脚本:
若想要学习代码,可用展示模式,runApp("my_app", display.mode = "showcase")
:
Ref:
https://shiny.rstudio.com/tutorial/written-tutorial/lesson1/