R Shiny App 佈局:shinydashboard 設置背景 #結構概要 #原文:

shinydashboard包提供了一組用於創建生成儀表板的HTML的函數。

#結構概要

dashboardPage()函數包含三個組件:

  • a header
  • sidebar
  • body
dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody()
)

或者

header <- dashboardHeader()
sidebar <- dashboardSidebar()
body <- dashboardBody()
dashboardPage(header, sidebar, body)

##Header

標題可以有標題和下拉菜單。

  • 標題:創建使用參數title

  • 下拉菜單:創建使用函數dropdownMenu(),下拉菜單有三種:

    • messages
    • notifications
    • tasks

###Message menus

下拉菜單中組成使用messageItem()

messageItem(from, message, icon = shiny::icon("user"), time = NULL,
  href = NULL)
dropdownMenu(type = "messages",
  messageItem(
    from = "Sales Dept",
    message = "Sales are steady this month."
  ),
  messageItem(
    from = "New User",
    message = "How do I register?",
    icon = icon("question"),
    time = "13:45"
  ),
  messageItem(
    from = "Support",
    message = "The new server is ready.",
    icon = icon("life-ring"),
    time = "2014-12-01"
  )
)

###動態內容

創建方法:

UI中:

dashboardHeader(dropdownMenuOutput("messageMenu"))

server中:

output$messageMenu <- renderMenu({
  # Code to generate each of the messageItems here, in a list. This assumes
  # that messageData is a data frame with two columns, 'from' and 'message'.
  msgs <- apply(messageData, 1, function(row) {
    messageItem(from = row[["from"]], message = row[["message"]])
  })

  # This is equivalent to calling:
  #   dropdownMenu(type="messages", msgs[[1]], msgs[[2]], ...)
  dropdownMenu(type = "messages", .list = msgs)
})

###通知菜單

dropdownMenu(type = "notifications",
  notificationItem(
    text = "5 new users today",
    icon("users")
  ),
  notificationItem(
    text = "12 items delivered",
    icon("truck"),
    status = "success"
  ),
  notificationItem(
    text = "Server load at 86%",
    icon = icon("exclamation-triangle"),
    status = "warning"
  )
)

###任務菜單

dropdownMenu(type = "tasks", badgeStatus = "success",
  taskItem(value = 90, color = "green",
    "Documentation"
  ),
  taskItem(value = 17, color = "aqua",
    "Project X"
  ),
  taskItem(value = 75, color = "yellow",
    "Server deployment"
  ),
  taskItem(value = 80, color = "red",
    "Overall project"
  )
)

### ###禁用標題欄

dashboardHeader(disable = TRUE)

## ##Sidebar

###Sidebar menu items and tabs

當單擊一個鏈接時,它將在儀表板的主體中顯示不同的內容。

與Shiny中的tabPanel類似。

注:必須保證dashboardSidebar中menuItem的tabName 與dashboardBody中tabItem的tabName 是一樣的,這樣才能對應。

## ui.R ##
sidebar <- dashboardSidebar(
  sidebarMenu(
    menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")),
    menuItem("Widgets", icon = icon("th"), tabName = "widgets",
             badgeLabel = "new", badgeColor = "green")
  )
)

body <- dashboardBody(
  tabItems(
    tabItem(tabName = "dashboard",
      h2("Dashboard tab content")
    ),

    tabItem(tabName = "widgets",
      h2("Widgets tab content")
    )
  )
)

# Put them together into a dashboardPage
dashboardPage(
  dashboardHeader(title = "Simple tabs"),
  sidebar,
  body
)

menuItems的圖標可以使用Shiny中函數icon()改變。

各種各樣的圖標參考:

Skins Icons

Font-Awesome

Glyphicons

默認情況下,icon()函數使用來自Font-Awesome的圖標。使用glyphicon,請使用lib="glyphicon")

"Calendar from Font-Awesome:", icon("calendar"),
"Cog from Glyphicons:", icon("cog", lib = "glyphicon")

menuItem中也可以提供鏈接,從而訪問外部網站:

 menuItem("Source code", icon = icon("file-code-o"), 
           href = "https://github.com/rstudio/shinydashboard/")

###Bookmarking and restoring selected tabs

Shiny可以添加書籤並恢復應用程序的狀態。在使用shinydashboard構建的應用程序中,要想添加書籤並恢復選中的選項,你必須使用id調用sidebarMenu()。

sidebarMenu(id = "sidebar",
  ....
)

詳細操作查看: bookmark and restore

###動態內容

可以使用renderMenu和sidebarMenuOutput動態生成側邊欄菜單。

ui <- dashboardPage(
  dashboardHeader(title = "Dynamic sidebar"),
  dashboardSidebar(
    sidebarMenuOutput("menu")
  ),
  dashboardBody()
)

server <- function(input, output) {
  output$menu <- renderMenu({
    sidebarMenu(
      menuItem("Menu item", icon = icon("calendar"))
    )
  })
}

shinyApp(ui, server)

ui <- dashboardPage(
  dashboardHeader(title = "Dynamic sidebar"),
  dashboardSidebar(
    sidebarMenu(
      menuItemOutput("menuitem")
    )
  ),
  dashboardBody()
)

server <- function(input, output) {
  output$menuitem <- renderMenu({
    menuItem("Menu item", icon = icon("calendar"))
  })
}

shinyApp(ui, server)

###側邊欄中的輸入

 sidebarSearchForm(textId = "searchText", buttonId = "searchButton",
                    label = "Search...")

對於這個搜索,server代碼中的對應值將是inputsearchText和inputsearchButton。

###禁用側邊欄

dashboardSidebar(disable = TRUE)

##Body

儀表板頁面的主體可以包含任何規則的shiny內容。然而,如果正在創建一個指示板,可能想要創建一些更結構化的東西。儀表板的基本構造是box()。box()中可以包含任何內容。

###Boxes

box是儀表板頁面的主要構建塊。可以使用box()函數創建一個基本框,box的內容可以是任何shiny UI內容。

在典型的儀表板中,box將被放置在一個fluidRow()中.

# This is just the body component of a dashboard
dashboardBody(
  fluidRow(
    box(plotOutput("plot1")),
    
    box(
      "Box content here", br(), "More box content",
      sliderInput("slider", "Slider input:", 1, 100, 50),
      textInput("text", "Text input:")
    )
  )
)

####Basic boxes

box可以有標題,並且標題和標題欄顏色可以通過titlestatus設置。

  • Statuses

  • status="primary"`, `status="success"
    
  • colors

  • color="red"`, `color="black"
    

注:狀態和顏色可以通過?validStatuses和?validColors查看。

box(title = "Histogram", status = "primary", plotOutput("plot2", height = 250)),

box(
  title = "Inputs", status = "warning",
  "Box content here", br(), "More box content",
  sliderInput("slider", "Slider input:", 1, 100, 50),
  textInput("text", "Text input:")
)

####Box header color and title

使用solidHeader=TRUE設置實標頭,並在右上角顯示一個按鈕,該按鈕將以collapsible=TRUE摺疊該框:

box(
  title = "Histogram", status = "primary", solidHeader = TRUE,
  collapsible = TRUE,
  plotOutput("plot3", height = 250)
),

box(
  title = "Inputs", status = "warning", solidHeader = TRUE,
  "Box content here", br(), "More box content",
  sliderInput("slider", "Slider input:", 1, 100, 50),
  textInput("text", "Text input:")
)

####Solid header and collapse

如果希望方框頂部沒有灰色或有色條,請使用solidHeader=TRUE,並且不要爲狀態提供值:

box(
  title = "Histogram", solidHeader = TRUE,
  collapsible = TRUE,
  plotOutput("plot3", height = 250)
),

box(
  title = "Inputs", solidHeader = TRUE,
  "Box content here", br(), "More box content",
  sliderInput("slider", "Slider input:", 1, 100, 50),
  textInput("text", "Text input:")
)

####No colored bar

還可以使用background選項創建一個背景。

box(
  title = "Histogram", background = "maroon", solidHeader = TRUE,
  plotOutput("plot4", height = 250)
),

box(
  title = "Inputs", background = "black",
  "Box content here", br(), "More box content",
  sliderInput("slider", "Slider input:", 1, 100, 50),
  textInput("text", "Text input:")
)

####tabBox

  • tabBox

tabBox與Shiny 中tabsetPanel類似,tabPanels作爲輸入,允許您選擇選擇哪個tab,並可以分配一個id。

如果id是存在的,可以訪問哪個選項卡被選擇從服務器;在下面的示例中,使用輸入$tabset1訪問它。

tabBox與shinydashboard中box類似,可以修改height, width, 和title.

還可以使用side參數選擇選項卡出現在哪一邊。注意,如果side="right",選項卡將以相反的順序顯示。

body <- dashboardBody(
  fluidRow(
    tabBox(
      title = "First tabBox",
      # The id lets us use input$tabset1 on the server to find the current tab
      id = "tabset1", height = "250px",
      tabPanel("Tab1", "First tab content"),
      tabPanel("Tab2", "Tab content 2")
    ),
    tabBox(
      side = "right", height = "250px",
      selected = "Tab3",
      tabPanel("Tab1", "Tab content 1"),
      tabPanel("Tab2", "Tab content 2"),
      tabPanel("Tab3", "Note that when side=right, the tab order is reversed.")
    )
  ),
  fluidRow(
    tabBox(
      # Title can include an icon
      title = tagList(shiny::icon("gear"), "tabBox status"),
      tabPanel("Tab1",
        "Currently selected tab from first box:",
        verbatimTextOutput("tabset1Selected")
      ),
      tabPanel("Tab2", "Tab content 2")
    )
  )
)

shinyApp(
  ui = dashboardPage(
    dashboardHeader(title = "tabBoxes"),
    dashboardSidebar(),
    body
  ),
  server = function(input, output) {
    # The currently selected tab from the first box
    output$tabset1Selected <- renderText({
      input$tabset1
    })
  }
)

####infoBox

這是一種特殊的框,用於顯示簡單的數字或文本值,並帶有圖標。

第一行使用默認設置fill=FALSE,而第二行使用fill=TRUE。

由於infoBox的內容通常是動態的,因此shinydashboard包含了用於動態內容的幫助函數infoBoxOutput renderInfoBox。

library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Info boxes"),
  dashboardSidebar(),
  dashboardBody(
    # infoBoxes with fill=FALSE
    fluidRow(
      # A static infoBox
      infoBox("New Orders", 10 * 2, icon = icon("credit-card")),
      # Dynamic infoBoxes
      infoBoxOutput("progressBox"),
      infoBoxOutput("approvalBox")
    ),

    # infoBoxes with fill=TRUE
    fluidRow(
      infoBox("New Orders", 10 * 2, icon = icon("credit-card"), fill = TRUE),
      infoBoxOutput("progressBox2"),
      infoBoxOutput("approvalBox2")
    ),

    fluidRow(
      # Clicking this will increment the progress amount
      box(width = 4, actionButton("count", "Increment progress"))
    )
  )
)

server <- function(input, output) {
  output$progressBox <- renderInfoBox({
    infoBox(
      "Progress", paste0(25 + input$count, "%"), icon = icon("list"),
      color = "purple"
    )
  })
  output$approvalBox <- renderInfoBox({
    infoBox(
      "Approval", "80%", icon = icon("thumbs-up", lib = "glyphicon"),
      color = "yellow"
    )
  })

  # Same as above, but with fill=TRUE
  output$progressBox2 <- renderInfoBox({
    infoBox(
      "Progress", paste0(25 + input$count, "%"), icon = icon("list"),
      color = "purple", fill = TRUE
    )
  })
  output$approvalBox2 <- renderInfoBox({
    infoBox(
      "Approval", "80%", icon = icon("thumbs-up", lib = "glyphicon"),
      color = "yellow", fill = TRUE
    )
  })
}

shinyApp(ui, server)

###佈局

佈局方框需要了解一些引導網格佈局系統的知識。主體可以視爲被劃分爲12個等寬列和任意數量的行,可變高度的區域。當在網格中放置一個框(或其他項)時,可以指定希望它佔據12列中的多少列。在這個屏幕截圖中,第一行框的寬度各爲4列,第二列框的寬度各爲6列。

一般來說,有兩種方式來佈置方框:基於行的佈局,或者基於列的佈局。

####Row-based layout

在基於行的佈局中,框必須放在由fluidRow()創建的行中。行的網格寬度爲12,因此寬度=4的框佔寬度的三分之一,寬度=6(默認)的框佔寬度的一半。

在基於行的佈局中,每行框的頂部將對齊,但底部可能不對齊——這取決於每個框的內容。

body <- dashboardBody(
  fluidRow(
    box(title = "Box title", "Box content"),
    box(status = "warning", "Box content")
  ),

  fluidRow(
    box(
      title = "Title 1", width = 4, solidHeader = TRUE, status = "primary",
      "Box content"
    ),
    box(
      title = "Title 2", width = 4, solidHeader = TRUE,
      "Box content"
    ),
    box(
      title = "Title 1", width = 4, solidHeader = TRUE, status = "warning",
      "Box content"
    )
  ),

  fluidRow(
    box(
      width = 4, background = "black",
      "A box with a solid black background"
    ),
    box(
      title = "Title 5", width = 4, background = "light-blue",
      "A box with a solid light-blue background"
    ),
    box(
      title = "Title 6",width = 4, background = "maroon",
      "A box with a solid maroon background"
    )
  )
)

# We'll save it in a variable `ui` so that we can preview it in the console
ui <- dashboardPage(
  dashboardHeader(title = "Row layout"),
  dashboardSidebar(),
  body
)

# Preview the UI in the console
shinyApp(ui = ui, server = function(input, output) { })

通過設置height,可以強制所有框具有相同的高度。與使用12寬引導網格設置的寬度相反,高度是用像素指定的。

box(title = "Box title", height = 300, "Box content")

如果設置所有框的高度,可以得到這樣的儀表盤:

####Column-based layout

下面的代碼是這個基於列的佈局的基本框架。注意,在fluidRow中,有指定寬度的列,列中的每個框的width=NULL。

body <- dashboardBody(
  fluidRow(
    column(width = 4,
      box(
        title = "Box title", width = NULL, status = "primary",
        "Box content"
      ),
      box(
        title = "Title 1", width = NULL, solidHeader = TRUE, status = "primary",
        "Box content"
      ),
      box(
        width = NULL, background = "black",
        "A box with a solid black background"
      )
    ),

    column(width = 4,
      box(
        status = "warning", width = NULL,
        "Box content"
      ),
      box(
        title = "Title 3", width = NULL, solidHeader = TRUE, status = "warning",
        "Box content"
      ),
      box(
        title = "Title 5", width = NULL, background = "light-blue",
        "A box with a solid light-blue background"
      )
    ),

    column(width = 4,
      box(
        title = "Title 2", width = NULL, solidHeader = TRUE,
        "Box content"
      ),
      box(
        title = "Title 6", width = NULL, background = "maroon",
        "A box with a solid maroon background"
      )
    )
  )
)

# We'll save it in a variable `ui` so that we can preview it in the console
ui <- dashboardPage(
  dashboardHeader(title = "Column layout"),
  dashboardSidebar(),
  body
)

# Preview the UI in the console
shinyApp(ui = ui, server = function(input, output) { })

####Mixed row and column layout

也可以混合使用行和列。

body <- dashboardBody(
  fluidRow(
    box(
      title = "Box title", width = 6, status = "primary",
      "Box content"
    ),
    box(
      status = "warning", width = 6,
      "Box content"
    )
  ),
    
  fluidRow(
    column(width = 4,
      box(
        title = "Title 1", width = NULL, solidHeader = TRUE, status = "primary",
        "Box content"
      ),
      box(
        width = NULL, background = "black",
        "A box with a solid black background"
      )
    ),

    column(width = 4,
      box(
        title = "Title 3", width = NULL, solidHeader = TRUE, status = "warning",
        "Box content"
      ),
      box(
        title = "Title 5", width = NULL, background = "light-blue",
        "A box with a solid light-blue background"
      )
    ),

    column(width = 4,
      box(
        title = "Title 2", width = NULL, solidHeader = TRUE,
        "Box content"
      ),
      box(
        title = "Title 6", width = NULL, background = "maroon",
        "A box with a solid maroon background"
      )
    )
  )
)

# We'll save it in a variable `ui` so that we can preview it in the console
ui <- dashboardPage(
  dashboardHeader(title = "Mixed layout"),
  dashboardSidebar(),
  body
)

# Preview the UI in the console
shinyApp(ui = ui, server = function(input, output) { })

#原文:

Background: Shiny and HTML
shinydashboard

R shiny教程-1:一個 Shiny app的基本組成部分
R shiny教程-2:佈局用戶界面
R shiny教程-3:添加小部件到Shiny App
R shiny教程-4:Shiny app響應式結果展示
R shiny教程-5:調用R程序和導入數據
R shiny教程-6:使用響應表達式reactive()
R shiny教程-7:共享Shiny app
Shiny Server安裝
shinydashboard安裝、使用指南

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章