shinydashboard
## app.R ##
library(shiny)
library(shinydashboard)
ui <- dashboardPage(
#标题
dashboardHeader(title = "Basic dashboard"),
#侧边栏
dashboardSidebar(
sidebarMenu(
# 第一个参数是展示在界面的文本。tabName是在body中调用的。每次点击 menuItem会在body中出现一个新的页面。
# menuItem()需要放在sidebarMenu()中放在外面,会展示,但点击后没响应。
menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")),
menuItem("Widgets", tabName = "widgets", icon = icon("th")),
menuItem("表格示例:", tabName = "tab_budget", icon = icon("gear"))
),
# 非menuItem
selectInput("province", "地区:",
choices = list(
'安徽省' = 'p1',
'北京市' = 'p2'
)
),
#返回一个选项框,其中的选项会根据选择的省份而变化。
#使用uiOutput()创建动态UI元素。另外,也可以用DT包来展示表格数据,增加进度条等等
uiOutput("slt_store")
),
#body
dashboardBody(
#这些box需要放在行或列中
tabItems(
# 第一个菜单项,里面第一个参数是tabName,后面可以放html标签。
# tabItem()放在tabItems()中。
tabItem(tabName = "dashboard",
fluidRow(
#一个box就是一个框。最好放在column()中。
box(plotOutput("plot1", height = 250)),
box(
title = "Controls",
sliderInput("slider", "Number of observations:", 1, 100, 50)
),
#column()表示某一列,宽度为4,里面的元素是按行排列。
column(4,
wellPanel(
sliderInput("obs", "Number of observations:",
min = 1, max = 1000, value = 500)
),
wellPanel(
sliderInput("obs", "Number of observations:",
min = 1, max = 1000, value = 500)
),
wellPanel(
sliderInput("obs", "Number of observations:",
min = 1, max = 1000, value = 500)
)
),
column(8,
wellPanel(
sliderInput("obs", "Number of observations:",
min = 1, max = 1000, value = 500)
),
wellPanel(
sliderInput("obs", "Number of observations:",
min = 1, max = 1000, value = 500)
),
wellPanel(
sliderInput("obs", "Number of observations:",
min = 1, max = 1000, value = 500)
)
)
)
),
# Second tab content
tabItem(tabName = "widgets",
h2("Widgets tab content")
),
tabItem(tabName = "tab_budget",
fluidRow(
box(h1("示例"),
# 输出表格
tableOutput("df1")
)
)
)
)
)
)
server <- function(input, output) {
set.seed(122)
histdata <- rnorm(500)
#city_re()返回城市列表
city_re = reactive({
switch(input$province,
p1 = list("合肥市" = 'p11', '安庆市' = 'p12'),
p2 = list("朝阳" = 'p21', "昌平" = 'p22')
)
})
output$plot1 <- renderPlot({
data <- histdata[seq_len(input$slider)]
hist(data)
})
# 在server.R中使用renderUI()可以返回一个ui元素。
output$slt_store <- renderUI({
radioButtons("cities",
h3("城市:"),
city_re()
)
})
output$df1 <- renderTable({
data.frame(
a = c(1,2,3),
b = c(4,5,6)
)
})
}
shinyApp(ui, server)
DT包
可以对表格数据可视化
library(DT)
library(shiny)
ui <- basicPage(
h2("The mtcars data"),
DT::dataTableOutput("mytable")
)
server <- function(input, output) {
output$mytable = DT::renderDataTable({
mtcars
})
}
shinyApp(ui, server)