R+ECharts2Shiny實現web動態交互式可視化數據(上)

歡迎關注天善智能,我們是專注於商業智能BI,人工智能AI,大數據分析與挖掘領域的垂直社區,學習,問答、求職一站式搞定!

對商業智能BI、大數據分析挖掘、機器學習,python,R等數據領域感興趣的同學加微信:tstoutiao,邀請你進入數據愛好者交流羣,數據愛好者們都在這兒。

作者:糖甜甜甜,R語言中文社區專欄作者

公衆號:經管人學數據分析

前言

之前過年的時候有好友詢問,沒有太多web和開發的基礎,但是想在掌握R語言的基礎上,實現web動態交互式可視化公司的業務數據,百度的Echarts,它最初是爲了滿足企業商業體系裏各種業務系統(如鳳巢、廣告管家等等)的報表需求,後來發展成爲一個純Javascript的商業級數據圖表庫。但是對於普通沒有開發經驗的小白,無法完全能運用該庫到自己的web項目中,那麼R語言的ECharts2Shiny就可以輕鬆實現以上需求。

在學習ECharts2Shiny前,我們先來了解下如何用R Shiny包來構建應用程序。在掌握了Shiny後,即可輕鬆實現用ECharts2Shiny實現web動態交互式可視化數據。


1、Hello Shiny!

我們先從簡單的將Hello Shiny展示在你的應用程序上,效果如下,可以選擇在瀏覽器查看效果。

要運行這個例子,只需鍵入:

1library(shiny)
2runExample("01_hello")

Shiny應用程序分爲兩個部分:用戶界面定義和服務端腳本。

用戶界面是在源文件ui.R中定義的,這裏舉例在用戶界面展示一個生成正態分佈的隨機數,隨機數個數可以由用戶定義,並且繪製這些隨機數的直方圖:

UI.R

 1library(shiny)
2
3# Define UI for app that draws a histogram ----
4ui <- fluidPage(
5
6  # App title ----
7  titlePanel("Hello Shiny!"),
8
9  # Sidebar layout with input and output definitions ----
10  sidebarLayout(
11
12    # Sidebar panel for inputs ----
13    sidebarPanel(
14
15      # Input: Slider for the number of bins ----
16      sliderInput(inputId = "bins",
17                  label = "Number of bins:",
18                  min = 1,
19                  max = 50,
20                  value = 30)
21
22    ),
23
24    # Main panel for displaying outputs ----
25    mainPanel(
26
27      # Output: Histogram ----
28      plotOutput(outputId = "distPlot")
29
30    )
31  )
32)

服務端的代碼。生成給定個數的隨機變量,然後將直方圖畫出來。代碼中返回圖形的函數被renderPlot封裝後傳遞給output$distPlot。

server.R

 1# Define server logic required to draw a histogram ----
2server <- function(input, output) {
3
4  # Histogram of the Old Faithful Geyser Data ----
5  # with requested number of bins
6  # This expression that generates a histogram is wrapped in a call
7  # to renderPlot to indicate that:
8  #
9  # 1. It is "reactive" and therefore should be automatically
10  #    re-executed when inputs (input$bins) change
11  # 2. Its output type is a plot
12  output$distPlot <- renderPlot({
13
14    x    <- faithful$waiting
15    bins <- seq(min(x), max(x), length.out = input$bins + 1)
16
17    hist(x, breaks = bins, col = "#75AADB", border = "white",
18         xlab = "Waiting time to next eruption (in mins)",
19         main = "Histogram of waiting times")
20
21    })
22
23}
24
25# Create Shiny app ----
26shinyApp(ui = ui, server = server)

再來看一個例子,運行下面的代碼:


1runExample("02_text")


得到如下效果:

下面是用戶界面定義的代碼。sidebarPanel和mainPanel的函數調用中各有兩個參數對應於上面用戶界面中的左邊兩個輸入和右邊兩個輸出。

UI.R

 1library(shiny)
2
3# Define UI for dataset viewer app ----
4ui <- fluidPage(
5
6  # App title ----
7  titlePanel("Shiny Text"),
8
9  # Sidebar layout with a input and output definitions ----
10  sidebarLayout(
11
12    # Sidebar panel for inputs ----
13    sidebarPanel(
14
15      # Input: Selector for choosing dataset ----
16      selectInput(inputId = "dataset",
17                  label = "Choose a dataset:",
18                  choices = c("rock", "pressure", "cars")),
19
20      # Input: Numeric entry for number of obs to view ----
21      numericInput(inputId = "obs",
22                   label = "Number of observations to view:",
23                   value = 10)
24    ),
25
26    # Main panel for displaying outputs ----
27    mainPanel(
28
29      # Output: Verbatim text for data summary ----
30      verbatimTextOutput("summary"),
31
32      # Output: HTML table with requested number of observations ----
33      tableOutput("view")
34
35    )
36  )
37)


服務端的程序包括一個反應性表達式來返回用戶選擇的相應數據集。還有兩個渲染表達式renderPrint和renderTable來對應用戶的輸入返回輸入值到界面上。

server.R

 1# Define server logic to summarize and view selected dataset ----
2server <- function(input, output) {
3
4  # Return the requested dataset ----
5  datasetInput <- reactive({
6    switch(input$dataset,
7           "rock" = rock,
8           "pressure" = pressure,
9           "cars" = cars)
10  })
11
12  # Generate a summary of the dataset ----
13  output$summary <- renderPrint({
14    dataset <- datasetInput()
15    summary(dataset)
16  })
17
18  # Show the first "n" observations ----
19  output$view <- renderTable({
20    head(datasetInput(), n = input$obs)
21  })
22
23}
24
25# Create Shiny app ----
26shinyApp(ui = ui, server = server)

Shiny的web框架從本質上說是使從頁面中獲取輸入值並傳遞給R,然後把R代碼的結果以輸入值的形式返回給頁面。


Shiny的原理

shiny程序是個簡單的目錄,裏面包括用戶接口的定義、服務端腳本以及起支持作用的數據、腳本和其他資源。構建應用程序之初,先建一個空目錄,在這個目錄裏創建空文件UI.R 和 server.R

在構建自己的應用時,UI.R中有三個函數titlePanel、sidebarPanel和mainPanel定義了用戶接口的不同區域。titlePanel用來添加用戶界面的標題,比如前面例子中的Hello Shiny!和Shiny Text。sidebarPanel上添加輸入,比如前面的例子中的選擇框。mainPanel用來爲用戶接口顯示輸出,在主UI面板上添加元素來渲染在用戶界面的輸出值。

服務端實現定義程序的腳本,用來接收輸入,並計算輸出。server.R中調用shinyServer並傳遞給它一個函數,用來接收兩個參數:使用input對象的組件來訪問輸入,並通過向output對象的組件賦值來生成輸出。


到目前我們已經學會了如何用shiny創建一個自己的應用,在下一節中將介紹如何實現在shiny中調用Echarts包來實現將自己的業務數據可視化在web上。如果期待下節內容的話請在下面回覆、點下小卡片吧!


  • https://cran.r-project.org/web/packages/ECharts2Shiny/ECharts2Shiny.pdf

  • https://github.com/XD-DENG/ECharts2Shiny

  • http://yanping.me/shiny-tutorial/

  • 往期精彩:

  • 用人工智能方法計算水果難題------遺傳算法篇

  • R_空間插值_必知必會(一)

  • R語言網絡爬蟲經驗

  • R語言中文社區2018年終文章整理(作者篇)

  • R語言中文社區2018年終文章整理(類型篇)

  • 公衆號後臺回覆關鍵字即可學習

    回覆 爬蟲            爬蟲三大案例實戰
    回覆 Python       1小時破冰入門
    回覆 數據挖掘     R語言入門及數據挖掘
    回覆 人工智能     三個月入門人工智能
    回覆 數據分析師  數據分析師成長之路 
    回覆 機器學習     機器學習的商業應用
    回覆 數據科學     數據科學實戰
    回覆 常用算法     常用數據挖掘算法

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