本文共 10978 字,大约阅读时间需要 36 分钟。
r语言r-shiny
by AMR
通过AMR
One of the beautiful gifts that R has (that Python missed,until ) is . 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是一个R软件包,可以很容易地从R直接构建交互式Web应用程序。 仪表板之所以受欢迎,是因为它们很好地帮助企业从现有数据中获得洞察。
In this post, we will see how to leverage Shiny to build a simple sales revenue dashboard. You will need .
在这篇文章中,我们将看到如何利用Shiny构建一个简单的销售收入仪表板。 您将需要
The packages you need must be downloaded separately, and 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)
As a dashboard needs an input data to visualize, we will use 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 file into your current R session:
由于仪表板需要输入数据才能可视化,因此我们将使用作为向我们的仪表板输入数据的示例。 由于这是一个.csv文件,因此使用了read.csv命令。 .csv中的第一行是标题行,因此使用header = T。 您可以通过两种方式将文件放入当前的R会话中:
Open this link — and save it (Ctrl+S) in your , where this R code is saved. Then the following code will work perfectly.
打开此链接— 并将其(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
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 is an R package whose job is to make it easier, as the name suggests, to build dashboards with Shiny.
我们不仅将其仅使用Shiny , 其与结合 。 Shinydashboard是一个R包,其工作就是使它更容易使用Shiny来构建仪表板,顾名思义。
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()
是作为仪表盘标题可见。
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 . 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 . If you are interested in Shiny, you can learn more from DataCamp’s .
希望在此阶段,您可以启动并运行此示例Shiny Web应用程序。 上提供了此处使用的代码和绘图。 如果您对Shiny感兴趣,可以从DataCamp的了解更多信息。
翻译自:
r语言r-shiny
转载地址:http://wcgwd.baihongyu.com/