r語言r-shiny
by AMR
通過AMR
使用Shiny和R構建您的第一個Web應用程序儀表板 (Build your first web app dashboard using Shiny and R)
One of the beautiful gifts that R has (that Python missed,until dash) is Shiny. Shiny is an R package that makes it easy to build interactive web apps straight from R. Dashboards are popular since they are good in helping businesses make insights out of the existing data.
R擁有的漂亮禮物之一(Python漏掉了,直到破折號 )是Shiny 。 Shiny是一個R軟件包,可以很容易地從R直接構建交互式Web應用程序。 儀表板之所以受歡迎,是因為它們很好地幫助企業從現有數據中獲得洞察。
In this post, we will see how to leverage Shiny to build a simple sales revenue dashboard. You will need R installed.
在這篇文章中,我們將看到如何利用Shiny構建一個簡單的銷售收入儀表板。 您將需要安裝R。
在R中加載軟件包 (Loading packages in R)
The packages you need must be downloaded separately, and installed using R. All the packages listed below can be directly installed from CRAN, you can choose which CRAN mirror to use. Package dependencies will also be downloaded and installed by default.
您需要的軟件包必須單獨下載,并使用R 安裝 。 可以從CRAN直接安裝下面列出的所有軟件包,您可以選擇要使用的CRAN鏡像。 默認情況下,還將下載和安裝軟件包依賴項。
Once the packages are installed, you need to load them into your R session. The library and require commands are used and, again, package dependencies are also loaded automatically by R.
安裝軟件包后,您需要將它們加載到R會話中。 使用了library和require命令,并且包依賴關系也由R自動加載。
# load the required packageslibrary(shiny)require(shinydashboard)library(ggplot2)library(dplyr)
樣本輸入文件 (Sample input file)
As a dashboard needs an input data to visualize, we will use recommendation.csv as an example of input data to our dashboard. As this is a .csv file, the read.csv command was used. The first row in the .csv is a title row, so header=T is used. There are two ways you can get the recommendation.csv file into your current R session:
由于儀表板需要輸入數據才能可視化,因此我們將使用Recommendation.csv作為向我們的儀表板輸入數據的示例。 由于這是一個.csv文件,因此使用了read.csv命令。 .csv中的第一行是標題行,因此使用header = T。 您可以通過兩種方式將Recommendation.csv文件放入當前的R會話中:
Open this link — recommendation.csv and save it (Ctrl+S) in your current working directory, where this R code is saved. Then the following code will work perfectly.
打開此鏈接— Recommendation.csv 并將其(Ctrl + S) 保存在當前工作目錄中 ,該R代碼存儲在該目錄中。 然后,以下代碼將完美運行。
recommendation <- read.csv('recommendation.csv',stringsAsFactors = F,header=T)head(recommendation) Account Product Region Revenue1 Axis Bank FBB North 20002 HSBC FBB South 300003 SBI FBB East 10004 ICICI FBB West 10005 Bandhan Bank FBB West 2006 Axis Bank SIMO North 200
2. Instead of reading the .csv from your local computer, you can also read it from a URL (web) using the same function read.csv. Since this .csv is already uploaded on my Github, we can use that link in our read.csv to read the file.
2.除了從本地計算機讀取.csv之外,您還可以使用相同的read.csv函數從URL(Web)讀取它。 由于此.csv已經上傳到我的Github上,因此我們可以在read.csv中使用該鏈接來讀取文件。
recommendation <- read.csv('https://raw.githubusercontent.com/amrrs/sample_revenue_dashboard_shiny/master/recommendation.csv',stringsAsFactors = F,header=T)head(recommendation) Account Product Region Revenue1 Axis Bank FBB North 20002 HSBC FBB South 300003 SBI FBB East 10004 ICICI FBB West 10005 Bandhan Bank FBB West 2006 Axis Bank SIMO North 200
閃亮的概述 (Overview of Shiny)
Every Shiny application has two main sections: UI and Server. UI contains the code for front-end like buttons, plot visuals, tabs and so on. Server contains the code for back-end like data retrieval, manipulation, and wrangling.
每個Shiny應用程序都有兩個主要部分: UI和Server 。 UI包含前端代碼,如按鈕,繪圖視覺效果,選項卡等。 服務器包含用于后端的代碼,例如數據檢索,操作和整理。
Instead of simply using only Shiny, we couple it with shinydashboard. shinydashboard is an R package whose job is to make it easier, as the name suggests, to build dashboards with Shiny.
我們不僅將其僅使用Shiny , 還將其與Shinydashboard結合在一起 。 Shinydashboard是一個R包,其工作就是使它更容易使用Shiny來構建儀表板,顧名思義。
創建填充的儀表板:UI (Creating a populated dashboard: UI)
The UI part of a Shiny app built with shinydashboard has 3 basic elements wrapped in the dashboardPage() command. The simplest Shiny code with shinydashboard
使用Shinydashboard構建的Shiny應用程序的UI部分在dashboardPage()命令中包含3個基本元素。 最簡單的帶有Shinydashboard的 Shiny代碼
## app.R ##library(shiny)library(shinydashboard)ui <- dashboardPage( dashboardHeader(), dashboardSidebar(), dashboardBody())server <- function(input, output) { }shinyApp(ui, server)
gives this app
給這個程序
Let us populate dashboardHeader()
and dashboardSidebar()
. The code contains comments, prefixed with #.
讓我們填充dashboardHeader()
和dashboardSidebar()
。 該代碼包含以#開頭的注釋。
#Dashboard header carrying the title of the dashboardheader <- dashboardHeader(title = "Basic Dashboard") #Sidebar content of the dashboardsidebar <- dashboardSidebar( sidebarMenu( menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")), menuItem("Visit-us", icon = icon("send",lib='glyphicon'), href = "https://www.salesforce.com") ))
The UI elements that we would like to show in our dashboard populate dashboardPage()
. Since the example is a sales revenue dashboard, let us show three Key Performance Indicator (KPI) boxes on the top that represent a quick summary, followed by two box plots for a detailed view.
我們希望在儀表dashboardPage()
顯示的UI元素填充dashboardPage()
。 由于該示例是銷售收入儀表板,因此讓我們在頂部顯示三個關鍵績效指標(KPI)框,這些框代表一個快速摘要,然后是兩個框圖以獲取詳細視圖。
To align these elements, one by one, we define them inside fluidRow()
.
為了將這些元素一一對齊,我們在fluidRow()
內部定義它們。
frow1 <- fluidRow( valueBoxOutput("value1") ,valueBoxOutput("value2") ,valueBoxOutput("value3"))frow2 <- fluidRow( box( title = "Revenue per Account" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotOutput("revenuebyPrd", height = "300px") ) ,box( title = "Revenue per Product" ,status = "primary" ,solidHeader = TRUE ,collapsible = TRUE ,plotOutput("revenuebyRegion", height = "300px") ) )# combine the two fluid rows to make the bodybody <- dashboardBody(frow1, frow2)
In the above code, valueBoxOutput()
is used to display the KPI information. valueBoxOutput()
and plotOutput()
are written in the Server part, which is used in the UI part to display a plot. box()
is a function provided by shinydashboard
to enclose the plot inside a box that has features like title
, solidHeader
and collapsible
. Having defined two fluidRow()
functions individually for the sake of modularity, we combine both of them in dashbboardBody()
.
在上面的代碼中, valueBoxOutput()
用于顯示KPI信息。 valueBoxOutput()
和plotOutput()
編寫在Server部分中,該部分在UI部分中用于顯示繪圖。 box()
是shinydashboard
提供的函數,用于將圖封閉在具有title
, solidHeader
和collapsible
類的功能的solidHeader
。 為了模塊化,分別定義了兩個fluidRow()
函數,我們將它們都合并在dashbboardBody()
。
Thus we can complete the UI part, comprising header, sidebar, and page, with the code below:
因此,我們可以使用以下代碼完成UI部分,包括標題,側邊欄和頁面:
#completing the ui part with dashboardPageui <- dashboardPage(title = 'This is my Page title', header, sidebar, body, skin='red')
The value of title
in dashboardPage()
is the title of the browser page/tab, while the title defined in dashboardHeader()
is visible as the dashboard title.
的值title
中dashboardPage()
是瀏覽器頁面/選項卡的標題,而在限定的標題dashboardHeader()
是作為儀表盤標題可見。
創建填充的儀表板:服務器 (Creating a populated dashboard: Server)
With the UI part over, we will create the Server part where the program and logic behind valueBoxOutput()
and plotOutput()
are added with renderValueBox()
and renderPlot()
respectively. These are enclosed inside a server function
, with input
and output
as its parameters. Values inside input
are received from UI (like textBox
value, Slider
value). Values inside output
are sent to UI (like plotOutput
, valueBoxOutput
).
與UI部分結束后,我們將創造一個程序,背后的邏輯服務器部分valueBoxOutput()
和plotOutput()
被添加renderValueBox()
和renderPlot()
分別。 它們包含在server function
,并以input
和output
作為其參數。 input
內部的值是從UI接收的(例如textBox
值, Slider
值)。 output
中的值將發送到UI (例如plotOutput
, valueBoxOutput
)。
Below is the complete Server code:
以下是完整的服務器代碼:
# create the server functions for the dashboard server <- function(input, output) { #some data manipulation to derive the values of KPI boxes total.revenue <- sum(recommendation$Revenue) sales.account <- recommendation %>% group_by(Account) %>% summarise(value = sum(Revenue)) %>% filter(value==max(value)) prof.prod <- recommendation %>% group_by(Product) %>% summarise(value = sum(Revenue)) %>% filter(value==max(value))#creating the valueBoxOutput content output$value1 <- renderValueBox({ valueBox( formatC(sales.account$value, format="d", big.mark=',') ,paste('Top Account:',sales.account$Account) ,icon = icon("stats",lib='glyphicon') ,color = "purple") }) output$value2 <- renderValueBox({ valueBox( formatC(total.revenue, format="d", big.mark=',') ,'Total Expected Revenue' ,icon = icon("gbp",lib='glyphicon') ,color = "green") })output$value3 <- renderValueBox({ valueBox( formatC(prof.prod$value, format="d", big.mark=',') ,paste('Top Product:',prof.prod$Product) ,icon = icon("menu-hamburger",lib='glyphicon') ,color = "yellow") })#creating the plotOutput content output$revenuebyPrd <- renderPlot({ ggplot(data = recommendation, aes(x=Product, y=Revenue, fill=factor(Region))) + geom_bar(position = "dodge", stat = "identity") + ylab("Revenue (in Euros)") + xlab("Product") + theme(legend.position="bottom" ,plot.title = element_text(size=15, face="bold")) + ggtitle("Revenue by Product") + labs(fill = "Region") })output$revenuebyRegion <- renderPlot({ ggplot(data = recommendation, aes(x=Account, y=Revenue, fill=factor(Region))) + geom_bar(position = "dodge", stat = "identity") + ylab("Revenue (in Euros)") + xlab("Account") + theme(legend.position="bottom" ,plot.title = element_text(size=15, face="bold")) + ggtitle("Revenue by Region") + labs(fill = "Region") })}
So far, we have defined both essential parts of a Shiny app — UI and Server. Finally, we have to call/run the Shiny, with UI and Server as its parameters.
到目前為止,我們已經定義了一個閃亮的應用程序的兩個關鍵部分- UI和服務器 。 最后,我們必須調用/運行Shiny , 以UI和Server作為其參數。
#run/call the shiny appshinyApp(ui, server)Listening on http://127.0.0.1:5101
The entire R file has to be saved as app.R
inside a folder before running the shiny app. Also remember to put the input data file (in our case, recommendation.csv)
inside the same folder as app.R
. While there is another valid way to structure the Shiny app with two files ui.R
and server.R
(optionally, global.R
), it has been ignored in this article for the sake of brevity since this is aimed at beginners.
在 運行閃亮的應用程序 之前 ,必須將整個R文件另存為app.R
在一個文件夾內 。 還要記住,將輸入數據文件(在我們的示例中為app.R
recommendation.csv)
放入與app.R
相同的文件夾中。 盡管還有另一種有效的方法來構建具有兩個文件ui.R
和server.R
(可選地, global.R
)的Shiny應用程序,但為簡潔起見,本文中已將其忽略,因為它是針對初學者的。
Upon running the file, the Shiny web app will open in your default browser and look similar to the screenshots below:
運行文件后, Shiny Web應用程序將在默認瀏覽器中打開,外觀類似于以下屏幕截圖:
Hopefully, at this stage, you have this example Shiny web app up and running. The code and plots used here are available on my Github. If you are interested in Shiny, you can learn more from DataCamp’s Building Web Applications in R with Shiny Course.
希望在此階段,您可以啟動并運行此示例Shiny Web應用程序。 我的Github上提供了此處使用的代碼和繪圖。 如果您對Shiny感興趣,可以從DataCamp的R with Shiny Course構建Web應用程序中了解更多信息。
翻譯自: https://www.freecodecamp.org/news/build-your-first-web-app-dashboard-using-shiny-and-r-ec433c9f3f6c/
r語言r-shiny