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


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

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

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

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

前言

上篇文章中我們談到R語言中shiny包用作企業業務數據輕量級web開發的好處,

,在這篇文章中我們推薦下在Shiny Gallery上的用shiny開發出來的優秀網站,部分網站有代碼,大家可以在R中直接運行出來查看。


Shiny APP!


1.世界人口前景可視化web應用


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


GitHub地址:https://github.com/PPgp/wppExplorer

2.城市交通實時可視化web應用


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



GitHub地址:https://github.com/rstudio/shiny-examples/tree/master/086-bus-dashboard

3.美國非盈利大學可視化web應用


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


4.警力實時數據可視化web應用


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


GitHub地址:https://github.com/trestletech/dallas-police/

web應用中的部分功能的實現

以下的代碼可以直接複製粘貼在R中實現,通過從小功能的實現學習shiny包,平時爬取的數據可以選擇自己用R或python搭一個輕量級的web,為數據提供更多的價值,並且這樣的作品拿出來在面試數據分析職位會加不少分喲。

1.交互

在調用server函數,申明一個交互對象datasetInput,交互函數reactive用來對UI中的輸入進行處理,依賴於input$dataset,然後被output調用,這裡的數據可以是自己設定,excel、csv或者數據庫都可以。

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

39 verbatimTextOutput("summary"),
40
41 # Output: HTML table with requested number of observations ----
42 tableOutput("view")
43
44 )
45 )
46)
47
48# Define server logic to summarize and view selected dataset ----
49server 50
51 # Return the requested dataset ----
52 datasetInput 53 switch(input$dataset,
54 "rock" = rock,
55 "pressure" = pressure,
56 "cars" = cars)
57 })
58
59 # Create caption ----
60 output$caption 61 input$caption
62 })
63
64 # Generate a summary of the dataset ----
65 output$summary 66 dataset 67 summary(dataset)
68 })
69
70 # Show the first "n" observations ----
71 output$view 72 head(datasetInput(), n = input$obs)
73 })
74}
75
76shinyApp(ui, server)

2.控件

shiny中關於控件的函數比較多,不同的數據輸入可以由多個控件來控制,更方便的由各個業務角度來展示數據。

 1library(shiny)
2
3# Define UI for slider demo app ----
4ui 5
6 # App title ----
7 titlePanel("Sliders"),

8
9 # Sidebar layout with input and output definitions ----
10 sidebarLayout(
11
12 # Sidebar to demonstrate various slider options ----
13 sidebarPanel(
14
15 # Input: Simple integer interval ----
16 sliderInput("integer", "Integer:",
17 min = 0, max = 1000,
18 value = 500),
19
20 # Input: Decimal interval with step value ----
21 sliderInput("decimal", "Decimal:",
22 min = 0, max = 1,
23 value = 0.5, step = 0.1),
24
25 # Input: Specification of range within an interval ----
26 sliderInput("range", "Range:",
27 min = 1, max = 1000,
28 value = c(200,500)),
29
30 # Input: Custom currency format for with basic animation ----
31 sliderInput("format", "Custom Format:",
32 min = 0, max = 10000,
33 value = 0, step = 2500,
34 pre = "$", sep = ",",
35 animate = TRUE),
36
37 # Input: Animation with custom interval (in ms) ----
38 # to control speed, plus looping
39 sliderInput("animation", "Looping Animation:",
40 min = 1, max = 2000,
41 value = 1, step = 10,
42 animate =
43 animationOptions(interval = 300, loop = TRUE))
44
45 ),
46
47 # Main panel for displaying outputs ----
48 mainPanel(
49
50 # Output: Table summarizing the values entered ----
51 tableOutput("values")
52
53 )
54 )
55)
56
57# Define server logic for slider examples ----

58server 59
60 # Reactive expression to create data frame of all input values ----
61 sliderValues 62
63 data.frame(
64 Name = c("Integer",
65 "Decimal",
66 "Range",
67 "Custom Format",
68 "Animation"),
69 Value = as.character(c(input$integer,
70 input$decimal,
71 paste(input$range, collapse = " "),
72 input$format,
73 input$animation)),
74 stringsAsFactors = FALSE)
75
76 })
77
78 # Show the values in an HTML table ----
79 output$values 80 sliderValues()
81 })
82
83}
84
85# Create Shiny app ----
86shinyApp(ui, server)

3.UI引用HTML文件

UI可以完全引用HTML文件,為用戶界面加上豐富的樣式和交互,但是寫HTML文件需要了解html、css和js等內容。

UI部分的.html

 1
2
3
4
5
6 <link>
7
8

9
10
11

HTML UI


12
13


14 <label>Distribution type:/<label>

15 <select>
16 <option>Normal/<option>
17 <option>Uniform/<option>
18 <option>Log-normal/<option>
19 <option>Exponential/<option>
20 /<select>
21


22
23


24
25 <label>Number of observations:/<label>

26
27
28


29
30

Summary of data:


31

32
33

Plot of data:


34
35 style="width: 100%; height: 300px">

36
37

Head of data:


38

39
40
41

server.R

 1library(shiny)
2
3# Define server logic for random distribution app ----
4server 5
6 # Reactive expression to generate the requested distribution ----
7 # This is called whenever the inputs change. The output functions
8 # defined below then use the value computed from this expression
9 d 10 dist 11 norm = rnorm,
12 unif = runif,
13 lnorm = rlnorm,
14 exp = rexp,
15 rnorm)
16
17 dist(input$n)
18 })
19
20 # Generate a plot of the data ----
21 # Also uses the inputs to build the plot label. Note that the
22 # dependencies on the inputs and the data reactive expression are
23 # both tracked, and all expressions are called in the sequence
24 # implied by the dependency graph.
25 output$plot 26 dist 27 n 28
29 hist(d(),
30 main = paste("r", dist, "(", n, ")", sep = ""),
31 col = "#75AADB", border = "white")
32 })
33
34 # Generate a summary of the data ----
35 output$summary 36 summary(d())
37 })
38
39 # Generate an HTML table view of the head of the data ----
40 output$table 41 head(data.frame(x = d()))
42 })
43
44}
45
46# Create Shiny app ----
47shinyApp(ui = htmlTemplate("www/index.html"), server)

4.文件上傳

在UI部分加入fileInput函數,在server函數中用input$file來實現文件上載功能。

 1library(shiny)
2
3# Define UI for data upload app ----
4ui 5
6 # App title ----
7 titlePanel("Uploading Files"),
8
9 # Sidebar layout with input and output definitions ----
10 sidebarLayout(
11
12 # Sidebar panel for inputs ----
13 sidebarPanel(
14
15 # Input: Select a file ----
16 fileInput("file1", "Choose CSV File",
17 multiple = FALSE,
18 accept = c("text/csv",
19 "text/comma-separated-values,text/plain",
20 ".csv")),
21
22 # Horizontal line ----
23 tags$hr(),
24
25 # Input: Checkbox if file has header ----
26 checkboxInput("header", "Header", TRUE),
27
28 # Input: Select separator ----
29 radioButtons("sep", "Separator",
30 choices = c(Comma = ",",
31 Semicolon = ";",
32 Tab = "\t"),
33 selected = ","),
34
35 # Input: Select quotes ----
36 radioButtons("quote", "Quote",
37 choices = c(None = "",
38 "Double Quote" = '"',
39 "Single Quote" = "'"),
40 selected = '"'),
41
42 # Horizontal line ----
43 tags$hr(),
44
45 # Input: Select number of rows to display ----
46 radioButtons("disp", "Display",

47 choices = c(Head = "head",
48 All = "all"),
49 selected = "head")
50
51 ),
52
53 # Main panel for displaying outputs ----
54 mainPanel(
55
56 # Output: Data file ----
57 tableOutput("contents")
58
59 )
60
61 )
62)
63
64# Define server logic to read selected file ----
65server 66
67 output$contents 68
69 # input$file1 will be NULL initially. After the user selects
70 # and uploads a file, head of that data file by default,
71 # or all rows if selected, will be shown.
72
73 req(input$file1)
74
75 # when reading semicolon separated files,
76 # having a comma separator causes `read.csv` to error
77 tryCatch(
78 {
79 df 80 header = input$header,
81 sep = input$sep,
82 quote = input$quote)
83 },
84 error = function(e) {
85 # return a safeError if a parsing error occurs
86 stop(safeError(e))
87 }
88 )
89
90 if(input$disp == "head") {
91 return(head(df))
92 }
93 else {
94 return(df)
95 }
96
97 })
98
99}

100
101# Create Shiny app ----
102shinyApp(ui, server)

5.文件下載

在UI部分使用downloadButton函數,在server函數中用downloadHandler來實現文件下載功能。

 1library(shiny)
2
3# Define UI for data download app ----
4ui 5
6 # App title ----
7 titlePanel("Downloading Data"),
8
9 # Sidebar layout with input and output definitions ----
10 sidebarLayout(
11
12 # Sidebar panel for inputs ----
13 sidebarPanel(
14
15 # Input: Choose dataset ----
16 selectInput("dataset", "Choose a dataset:",
17 choices = c("rock", "pressure", "cars")),
18
19 # Button
20 downloadButton("downloadData", "Download")
21
22 ),
23
24 # Main panel for displaying outputs ----
25 mainPanel(
26
27 tableOutput("table")
28
29 )
30
31 )
32)
33
34# Define server logic to display and download selected file ----
35server 36
37 # Reactive value for selected dataset ----
38 datasetInput 39 switch(input$dataset,
40 "rock" = rock,

41 "pressure" = pressure,
42 "cars" = cars)
43 })
44
45 # Table of selected dataset ----
46 output$table 47 datasetInput()
48 })
49
50 # Downloadable csv of selected dataset ----
51 output$downloadData 52 filename = function() {
53 paste(input$dataset, ".csv", sep = "")
54 },
55 content = function(file) {
56 write.csv(datasetInput(), file, row.names = FALSE)
57 }
58 )
59
60}
61
62# Create Shiny app ----
63shinyApp(ui, server)


參考

1、https://github.com/rstudio/shiny-examples


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



往期精彩:


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


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


分享到:


相關文章: