700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > R+ECharts2Shiny实现web动态交互式可视化数据(中)

R+ECharts2Shiny实现web动态交互式可视化数据(中)

时间:2023-08-05 14:44:50

相关推荐

R+ECharts2Shiny实现web动态交互式可视化数据(中)

欢迎关注天善智能,我们是专注于商业智能BI,人工智能AI,大数据分析与挖掘领域的垂直社区,学习,问答、求职一站式搞定!

对商业智能BI、大数据分析挖掘、机器学习,python,R等数据领域感兴趣的同学加微信:tstoutiao,邀请你进入数据爱好者交流群,数据爱好者们都在这儿。

作者:糖甜甜甜,R语言中文社区专栏作者

公众号:经管人学数据分析

前言

上篇文章中我们谈到R语言中shiny包用作企业业务数据轻量级web开发的好处,

R+ECharts2Shiny实现web动态交互式可视化数据(上)

,在这篇文章中我们推荐下在Shiny Gallery上的用shiny开发出来的优秀网站,部分网站有代码,大家可以在R中直接运行出来查看。

Shiny APP!

1.世界人口前景可视化web应用

GitHub地址:/PPgp/wppExplorer

2.城市交通实时可视化web应用

GitHub地址:/rstudio/shiny-examples/tree/master/086-bus-dashboard

3.美国非盈利大学可视化web应用

4.警力实时数据可视化web应用

GitHub地址:/trestletech/dallas-police/

web应用中的部分功能的实现

以下的代码可以直接复制粘贴在R中实现,通过从小功能的实现学习shiny包,平时爬取的数据可以选择自己用R或python搭一个轻量级的web,为数据提供更多的价值,并且这样的作品拿出来在面试数据分析职位会加不少分哟。

1.交互

在调用server函数,申明一个交互对象datasetInput,交互函数reactive用来对UI中的输入进行处理,依赖于input$dataset,然后被output调用,这里的数据可以是自己设定,excel、csv或者数据库都可以。

1library(shiny)

2

3#DefineUIfordatasetviewerapp----

4ui<-fluidPage(

5

6#Apptitle----

7titlePanel("Reactivity"),

8

9#Sidebarlayoutwithinputandoutputdefinitions----

10sidebarLayout(

11

12#Sidebarpanelforinputs----

13sidebarPanel(

14

15#Input:Textforprovidingacaption----

16textInput(inputId="caption",

17label="Caption:",

18value="DataSummary"),

19

20#Input:Selectorforchoosingdataset----

21selectInput(inputId="dataset",

22label="Chooseadataset:",

23choices=c("rock","pressure","cars")),

24

25#Input:Numericentryfornumberofobstoview----

26numericInput(inputId="obs",

27label="Numberofobservationstoview:",

28value=10)

29

30),

31

32#Mainpanelfordisplayingoutputs----

33mainPanel(

34

35#Output:Formattedtextforcaption----

36h3(textOutput("caption",container=span)),

37

38#Output:Verbatimtextfordatasummary----

39verbatimTextOutput("summary"),

40

41#Output:HTMLtablewithrequestednumberofobservations----

42tableOutput("view")

43

44)

45)

46)

47

48#Defineserverlogictosummarizeandviewselecteddataset----

49server<-function(input,output){

50

51#Returntherequesteddataset----

52datasetInput<-reactive({

53switch(input$dataset,

54"rock"=rock,

55"pressure"=pressure,

56"cars"=cars)

57})

58

59#Createcaption----

60output$caption<-renderText({

61input$caption

62})

63

64#Generateasummaryofthedataset----

65output$summary<-renderPrint({

66dataset<-datasetInput()

67summary(dataset)

68})

69

70#Showthefirst"n"observations----

71output$view<-renderTable({

72head(datasetInput(),n=input$obs)

73})

74}

75

76shinyApp(ui,server)

2.控件

shiny中关于控件的函数比较多,不同的数据输入可以由多个控件来控制,更方便的由各个业务角度来展示数据。

1library(shiny)

2

3#DefineUIforsliderdemoapp----

4ui<-fluidPage(

5

6#Apptitle----

7titlePanel("Sliders"),

8

9#Sidebarlayoutwithinputandoutputdefinitions----

10sidebarLayout(

11

12#Sidebartodemonstratevariousslideroptions----

13sidebarPanel(

14

15#Input:Simpleintegerinterval----

16sliderInput("integer","Integer:",

17min=0,max=1000,

18value=500),

19

20#Input:Decimalintervalwithstepvalue----

21sliderInput("decimal","Decimal:",

22min=0,max=1,

23value=0.5,step=0.1),

24

25#Input:Specificationofrangewithinaninterval----

26sliderInput("range","Range:",

27min=1,max=1000,

28value=c(200,500)),

29

30#Input:Customcurrencyformatforwithbasicanimation----

31sliderInput("format","CustomFormat:",

32min=0,max=10000,

33value=0,step=2500,

34pre="$",sep=",",

35animate=TRUE),

36

37#Input:Animationwithcustominterval(inms)----

38#tocontrolspeed,pluslooping

39sliderInput("animation","LoopingAnimation:",

40min=1,max=2000,

41value=1,step=10,

42animate=

43animationOptions(interval=300,loop=TRUE))

44

45),

46

47#Mainpanelfordisplayingoutputs----

48mainPanel(

49

50#Output:Tablesummarizingthevaluesentered----

51tableOutput("values")

52

53)

54)

55)

56

57#Defineserverlogicforsliderexamples----

58server<-function(input,output){

59

60#Reactiveexpressiontocreatedataframeofallinputvalues----

61sliderValues<-reactive({

62

63data.frame(

64Name=c("Integer",

65"Decimal",

66"Range",

67"CustomFormat",

68"Animation"),

69Value=as.character(c(input$integer,

70input$decimal,

71paste(input$range,collapse=""),

72input$format,

73input$animation)),

74stringsAsFactors=FALSE)

75

76})

77

78#ShowthevaluesinanHTMLtable----

79output$values<-renderTable({

80sliderValues()

81})

82

83}

84

85#CreateShinyapp----

86shinyApp(ui,server)

3.UI引用HTML文件

UI可以完全引用HTML文件,为用户界面加上丰富的样式和交互,但是写HTML文件需要了解html、css和js等内容。

UI部分的.html

1<html>

2

3<head>

4<scriptsrc="shared/jquery.js"type="text/javascript"></script>

5<scriptsrc="shared/shiny.js"type="text/javascript"></script>

6<linkrel="stylesheet"type="text/css"href="shared/shiny.css"/>

7</head>

8

9<body>

10

11<h1>HTMLUI</h1>

12

13<p>

14<label>Distributiontype:</label><br/>

15<selectname="dist">

16<optionvalue="norm">Normal</option>

17<optionvalue="unif">Uniform</option>

18<optionvalue="lnorm">Log-normal</option>

19<optionvalue="exp">Exponential</option>

20</select>

21</p>

22

23<p>

24

25<label>Numberofobservations:</label><br/>

26<inputtype="number"name="n"value="500"min="1"max="1000"/>

27

28</p>

29

30<h3>Summaryofdata:</h3>

31<preid="summary"class="shiny-text-output"></pre>

32

33<h3>Plotofdata:</h3>

34<divid="plot"class="shiny-plot-output"

35style="width:100%;height:300px"></div>

36

37<h3>Headofdata:</h3>

38<divid="table"class="shiny-html-output"></div>

39

40</body>

41</html>

server.R

1library(shiny)

2

3#Defineserverlogicforrandomdistributionapp----

4server<-function(input,output){

5

6#Reactiveexpressiontogeneratetherequesteddistribution----

7#Thisiscalledwhenevertheinputschange.Theoutputfunctions

8#definedbelowthenusethevaluecomputedfromthisexpression

9d<-reactive({

10dist<-switch(input$dist,

11norm=rnorm,

12unif=runif,

13lnorm=rlnorm,

14exp=rexp,

15rnorm)

16

17dist(input$n)

18})

19

20#Generateaplotofthedata----

21#Alsousestheinputstobuildtheplotlabel.Notethatthe

22#dependenciesontheinputsandthedatareactiveexpressionare

23#bothtracked,andallexpressionsarecalledinthesequence

24#impliedbythedependencygraph.

25output$plot<-renderPlot({

26dist<-input$dist

27n<-input$n

28

29hist(d(),

30main=paste("r",dist,"(",n,")",sep=""),

31col="#75AADB",border="white")

32})

33

34#Generateasummaryofthedata----

35output$summary<-renderPrint({

36summary(d())

37})

38

39#GenerateanHTMLtableviewoftheheadofthedata----

40output$table<-renderTable({

41head(data.frame(x=d()))

42})

43

44}

45

46#CreateShinyapp----

47shinyApp(ui=htmlTemplate("www/index.html"),server)

4.文件上传

在UI部分加入fileInput函数,在server函数中用input$file来实现文件上载功能。

1library(shiny)

2

3#DefineUIfordatauploadapp----

4ui<-fluidPage(

5

6#Apptitle----

7titlePanel("UploadingFiles"),

8

9#Sidebarlayoutwithinputandoutputdefinitions----

10sidebarLayout(

11

12#Sidebarpanelforinputs----

13sidebarPanel(

14

15#Input:Selectafile----

16fileInput("file1","ChooseCSVFile",

17multiple=FALSE,

18accept=c("text/csv",

19"text/comma-separated-values,text/plain",

20".csv")),

21

22#Horizontalline----

23tags$hr(),

24

25#Input:Checkboxiffilehasheader----

26checkboxInput("header","Header",TRUE),

27

28#Input:Selectseparator----

29radioButtons("sep","Separator",

30choices=c(Comma=",",

31Semicolon=";",

32Tab="\t"),

33selected=","),

34

35#Input:Selectquotes----

36radioButtons("quote","Quote",

37choices=c(None="",

38"DoubleQuote"='"',

39"SingleQuote"="'"),

40selected='"'),

41

42#Horizontalline----

43tags$hr(),

44

45#Input:Selectnumberofrowstodisplay----

46radioButtons("disp","Display",

47choices=c(Head="head",

48All="all"),

49selected="head")

50

51),

52

53#Mainpanelfordisplayingoutputs----

54mainPanel(

55

56#Output:Datafile----

57tableOutput("contents")

58

59)

60

61)

62)

63

64#Defineserverlogictoreadselectedfile----

65server<-function(input,output){

66

67output$contents<-renderTable({

68

69#input$file1willbeNULLinitially.Aftertheuserselects

70#anduploadsafile,headofthatdatafilebydefault,

71#orallrowsifselected,willbeshown.

72

73req(input$file1)

74

75#whenreadingsemicolonseparatedfiles,

76#havingacommaseparatorcauses`read.csv`toerror

77tryCatch(

78{

79df<-read.csv(input$file1$datapath,

80header=input$header,

81sep=input$sep,

82quote=input$quote)

83},

84error=function(e){

85#returnasafeErrorifaparsingerroroccurs

86stop(safeError(e))

87}

88)

89

90if(input$disp=="head"){

91return(head(df))

92}

93else{

94return(df)

95}

96

97})

98

99}

100

101#CreateShinyapp----

102shinyApp(ui,server)

5.文件下载

在UI部分使用downloadButton函数,在server函数中用downloadHandler来实现文件下载功能。

1library(shiny)

2

3#DefineUIfordatadownloadapp----

4ui<-fluidPage(

5

6#Apptitle----

7titlePanel("DownloadingData"),

8

9#Sidebarlayoutwithinputandoutputdefinitions----

10sidebarLayout(

11

12#Sidebarpanelforinputs----

13sidebarPanel(

14

15#Input:Choosedataset----

16selectInput("dataset","Chooseadataset:",

17choices=c("rock","pressure","cars")),

18

19#Button

20downloadButton("downloadData","Download")

21

22),

23

24#Mainpanelfordisplayingoutputs----

25mainPanel(

26

27tableOutput("table")

28

29)

30

31)

32)

33

34#Defineserverlogictodisplayanddownloadselectedfile----

35server<-function(input,output){

36

37#Reactivevalueforselecteddataset----

38datasetInput<-reactive({

39switch(input$dataset,

40"rock"=rock,

41"pressure"=pressure,

42"cars"=cars)

43})

44

45#Tableofselecteddataset----

46output$table<-renderTable({

47datasetInput()

48})

49

50#Downloadablecsvofselecteddataset----

51output$downloadData<-downloadHandler(

52filename=function(){

53paste(input$dataset,".csv",sep="")

54},

55content=function(file){

56write.csv(datasetInput(),file,row.names=FALSE)

57}

58)

59

60}

61

62#CreateShinyapp----

63shinyApp(ui,server)

参考

1、/rstudio/shiny-examples

往期精彩:

R+ECharts2Shiny实现web动态交互式可视化数据(上)

R_空间插值_必知必会(二)

用人工智能方法计算水果难题------遗传算法篇

R语言中文社区终文章整理(作者篇)

R语言中文社区终文章整理(类型篇)

公众号后台回复关键字即可学习

回复爬虫爬虫三大案例实战

回复Python1小时破冰入门

回复数据挖掘R语言入门及数据挖掘

回复人工智能三个月入门人工智能

回复数据分析师数据分析师成长之路

回复机器学习机器学习的商业应用

回复数据科学数据科学实战

回复常用算法 常用数据挖掘算法

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。