-
Notifications
You must be signed in to change notification settings - Fork 72
/
cm109.Rmd
1033 lines (786 loc) · 33.4 KB
/
cm109.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# (9) DashR: Multi-level callbacks and layouts
```{r include=FALSE}
knitr::opts_chunk$set(echo=TRUE, warning=FALSE, message=FALSE)
```
```{r}
library(tidyverse)
```
**This lecture is 100% complete.**
## Today's Agenda (10 mins)
- Announcements:
- [Assignment 05](https://stat545.stat.ubc.ca/evaluation/assignment_05/assignment_05/) and [Milestone 05](https://stat545.stat.ubc.ca/evaluation/milestone_05/milestone_05/) have now been posted
- Part 1: Effective Dashboards [25 mins]
- Principles of effective dashboards
- Other considerations for building dashboards
- Examples of effective dashboards
- Part 2: Multi-level callbacks in Dash [30 mins]
- Example 1: Linking two graphs together with clicks (by Sirine)
- Example 2: (Optional) Extra example linking graphs together (by Sirine)
- Part 3: Preview of Layouts in Dash [10 mins]
- Demo of layout possibilities
- Link to layout templates (by Matthew)
### Lecture Learning Objecives
By the end of this class you will :
- identify effective dashboards when you see them.
- apply principles of effective dashboards when creating your own.
- link two graphs together using multi-level callbacks.
- explore sample dashboard layouts.
- The [repl.it](https://repl.it/join/zjzcanpx-firasm) for today.
## Part 1: Effective Dashboards [25 mins]
The slides for this section can be found [here](https://github.com/firasm/bits/raw/master/2020-03-23%20-%20Effective%20Dashboards.pdf) and in your participation repo.
## Part 2: Part 2: Multi-level callbacks in Dash [30 mins]
Let's improve the app we created last time and add a line graph to it.
It's really difficult from this plot to identify the trend of particular countries.
Wouldn't it be good if could visualize the trend of GDP, population, or life expectancy for a particular country just by clicking on the top plot?
Here is the code we had at the end of last class:
```{app_origin_ex1}
# author: YOUR NAME
# date: THE DATE
"This script is the main file that creates a Dash app for cm108 on the gapminder dataset.
Usage: app.R
"
## Load libraries
library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)
library(dashTable)
library(tidyverse)
library(plotly)
library(gapminder)
## Make plot
make_plot <- function(yaxis = "gdpPercap",
scale = "linear"){
# gets the label matching the column value
y_label <- yaxisKey$label[yaxisKey$value==yaxis]
#filter our data based on the year/continent selections
data <- gapminder
# make the plot!
p <- ggplot(data, aes(x = year, y = !!sym(yaxis), colour = continent)) +
geom_jitter(alpha = 0.6) +
scale_color_manual(name = 'Continent', values = continent_colors) +
scale_x_continuous(breaks = unique(data$year))+
xlab("Year") +
ylab(y_label) +
ggtitle(paste0("Change in ", y_label, " over time (Scale : ", scale, ")")) +
theme_bw()
if (scale == 'log'){
p <- p + scale_y_continuous(trans='log10')
}
# passing c("text") into tooltip only shows the contents of
ggplotly(p, tooltip = c("text"))
}
## Assign components to variables
heading_title <- htmlH1('Gapminder Dash Demo')
heading_subtitle <- htmlH2('Looking at country data interactively')
# Storing the labels/values as a tibble means we can use this both
# to create the dropdown and convert colnames -> labels when plotting
yaxisKey <- tibble(label = c("GDP Per Capita", "Life Expectancy", "Population"),
value = c("gdpPercap", "lifeExp", "pop"))
#Create the dropdown
yaxisDropdown <- dccDropdown(
id = "y-axis",
options = map(
1:nrow(yaxisKey), function(i){
list(label=yaxisKey$label[i], value=yaxisKey$value[i])
}),
value = "gdpPercap"
)
#Create the button
logbutton <- dccRadioItems(
id = 'yaxis-type',
options = list(list(label = 'Linear', value = 'linear'),
list(label = 'Log', value = 'log')),
value = 'linear'
)
graph <- dccGraph(
id = 'gap-graph',
figure=make_plot() # gets initial data using argument defaults
)
sources <- dccMarkdown("[Data Source](https://cran.r-project.org/web/packages/gapminder/README.html)")
## Create Dash instance
app <- Dash$new()
## Specify App layout
app$layout(
htmlDiv(
list(
heading_title,
heading_subtitle,
#selection components
htmlLabel('Select y-axis metric:'),
yaxisDropdown,
htmlIframe(height=15, width=10, style=list(borderWidth = 0)), #space
htmlLabel('Select y scale : '),
logbutton,
#graph
graph,
htmlIframe(height=20, width=10, style=list(borderWidth = 0)), #space
sources
)
)
)
## App Callbacks
app$callback(
#update figure of gap-graph
output=list(id = 'gap-graph', property='figure'),
#based on values of year, continent, y-axis components
params=list(input(id = 'y-axis', property='value'),
input(id = 'yaxis-type', property='value')),
#this translates your list of params into function arguments
function(yaxis_value, yaxis_scale) {
make_plot(yaxis_value, yaxis_scale)
})
## Run app
app$run_server()
# command to add dash app in Rstudio viewer:
# rstudioapi::viewer("http://127.0.0.1:8050")
```
**Step 0 : create the new graph**
The first thing we have to do is to create the line graph and then add it to the your dashboard.
This plot should:
- be called `make_country_graph`
- have arguments `country_select` and `yaxis` with default values
```{make_line_graph_ex1}
## YOUR SOLUTION HERE
make_country_graph <- function(country_select="Canada",
yaxis="gdpPercap"){
# gets the label matching the column value
y_label <- yaxisKey$label[yaxisKey$value==yaxis]
#filter our data based on the year/continent selections
data <- gapminder %>%
filter(country == country_select)
# make the plot
p <- ggplot(data, aes(x=year, y=!!sym(yaxis), colour=continent)) +
geom_line() +
scale_color_manual(name="Continent", values=continent_colors) +
scale_x_continuous(breaks = unique(data$year))+
xlab("Year") +
ylab(y_label) +
ggtitle(paste0("Change in ", y_label, " Over Time: ",
country_select)) +
theme_bw()
ggplotly(p)
}
```
Now let's add this code to our app, create the corresponding Dash component, add component to the layout:
```{dash_component}
## YOUR SOLUTION HERE
graph_country <- dccGraph(
id = 'gap-graph-country',
figure=make_country_graph() # gets initial data using argument defaults
)
```
Now, if you did the two steps above correctly and run this app, you should see two graphs : the scatter plot we had last time, and a line graph.
The scatter plot should be dynamic (it should still change depending on what the user select in the dropdown menu), but the line graph won't change yet because haven't added the callbacks yet.
Now, let's link the two graphs together with callbacks!
**Step 1 : specify the action when you click on the first plot**
The first thing we have to do is to specify that clicking on the first graph is going to create an action and trigger a callback.
To do so, our code have to get the country name of the point clicked by the user.
For that, we are going to specify `customdata=country` in our plot aesthetics.
The `customdata` argument allows you to specify what information you want to save when the user clicks on this plot (here, it's the variable `country` that we want to keep).
Just adding `customdata=country` in the aesthetics would be enough, but I also recommand to change the way the plot looks when the user clicks on it, in order to highlight the selected point. To do so, we have to pip our ggplotly object into the `layout(clickmode = 'event+select')` function.
Let's introduce those two elements in the `make_plot` function.
```{specify_action_ex1}
ggplot(data, aes(x = year, y = !!sym(yaxis),
colour = continent,
customdata=country)) ### <- THIS PART NEEDS TO BE ADDED TO the ggplot object so we can "get" the country by clicking
```
There is one other (optional) enhancement we can make: by piping the ggplotly object to the `layout` function and specifying `clickmode = 'event+select'`, we can highlight the clicked point and dim the rest.
```{specify_action_ex1}
## Replace the end of the `make_plot` function with this snippet
ggplotly(p) %>%
####NEW: this is optional but changes how the graph appears on click
# more layout stuff: https://plotly-r.com/improving-ggplotly.html
layout(clickmode = 'event+select')
}
```
**Step 2 : create the callback**
Now, it's time to create the callback that is going to link our two graphs.
This is very similar to what we did in the previous lecture.
Let's focus on the `ouput` and `params` arguments first.
Try to fill in the blanks in the following code (note the 'clickData' property is new, we will look at it below).
```{callback_ex1}
output = list(id = <your_answer>, property = <your_answer>),
params = list(input(id=<your_answer>, property=<your_answer>),
# Here's where we check for graph interactions!
input(id=<your_answer>, property='clickData'))
## YOUR SOLUTION HERE
output = list(id = 'gap-graph-country', property = 'figure'),
params = list(input(id='y-axis', property='value'),
# Here's where we check for graph interactions!
input(id='gap-graph', property='clickData'))
```
*Hint* :
- There are 2 inputs : one corresponds to the value selected in the dropdown menu, and the other one is the point selected from the scatter plot.
- The proporty that corresponds to the graph is `clickData`
Now that we have the `output` and the `params` arguments specified, let's focus on the `function` .
This function is going to have two arguments, as we have two inputs. We can call those two arguments `yaxis_value` and `clickData`.
Then, inside this function, we are going to call our `make_country_graph` function, that we created in step 0.
The `make_country_graph` function takes two arguments : the country that we want to display, and the variable that we want to represent on the y-axis.
- The first argument is the tricky part! The information we need comes from the scatter plot so we need to get it out of `clickData`. However, there is a whole bunch of other stuff stored in `clickData` that we don't need so we need to dig around for it. To access the country name, we have to do the following : `clickData$points[[1]]$customdata`.
You can actually print out `clickData` to see all the information it contains.
- The second argument is not a problem, we can take the `yaxis_value` as we have done before.
With all those information at hand, our callback function looks like:
```{final_callback_ex1}
function(yaxis_value, clickData) {
# clickData contains $x, $y and $customdata
# you can't access these by gapminder column name!
country_name = clickData$points[[1]]$customdata
make_country_graph(country_name, yaxis_value)
})
```
Now, the last step is just to gather all the different chunks of code we created.
**Step 3 : put it all together**
Your final code should be similar to this:
```{app_final_ex1}
## YOUR SOLUTION HERE
# author: YOUR NAME
# date: THE DATE
"This script is the main file that creates a Dash app for cm109 on the gapminder dataset.
Usage: app.R
"
## Load libraries
library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)
library(dashTable)
library(tidyverse)
library(plotly)
library(gapminder)
## Make plot
make_plot <- function(yaxis = "gdpPercap",
scale = "linear"){
# gets the label matching the column value
y_label <- yaxisKey$label[yaxisKey$value==yaxis]
#filter our data based on the year/continent selections
data <- gapminder
# make the plot!
####NEW: the customdata mapping adds country to the tooltip and allows
# its selection using clickData.
p <- ggplot(data, aes(x = year, y = !!sym(yaxis),
colour = continent,
customdata=country)) +
geom_jitter(alpha=0.6) +
scale_color_manual(name = 'Continent', values = continent_colors) +
scale_x_continuous(breaks = unique(data$year))+
xlab("Year") +
ylab(y_label) +
ggtitle(paste0("Change in ", y_label, " over time (Scale : ", scale, ")")) +
theme_bw()
if (scale == 'log'){
p <- p + scale_y_continuous(trans='log10')
}
ggplotly(p) %>%
####NEW: this is optional but changes how the graph appears on click
# more layout stuff: https://plotly-r.com/improving-ggplotly.html
layout(clickmode = 'event+select')
}
####NEW : create the line graph
make_country_graph <- function(country_select="Canada",
yaxis="gdpPercap"){
# gets the label matching the column value
y_label <- yaxisKey$label[yaxisKey$value==yaxis]
#filter our data based on the year/continent selections
data <- gapminder %>%
filter(country == country_select)
# make the plot
p <- ggplot(data, aes(x=year, y=!!sym(yaxis), colour=continent)) +
geom_line() +
scale_color_manual(name="Continent", values=continent_colors) +
scale_x_continuous(breaks = unique(data$year))+
xlab("Year") +
ylab(y_label) +
ggtitle(paste0("Change in ", y_label, " Over Time: ",
country_select)) +
theme_bw()
ggplotly(p)
}
## Assign components to variables
heading_title <- htmlH1('Gapminder Dash Demo')
heading_subtitle <- htmlH2('Looking at country data interactively')
# Storing the labels/values as a tibble means we can use this both
# to create the dropdown and convert colnames -> labels when plotting
yaxisKey <- tibble(label = c("GDP Per Capita", "Life Expectancy", "Population"),
value = c("gdpPercap", "lifeExp", "pop"))
#Create the dropdown
yaxisDropdown <- dccDropdown(
id = "y-axis",
options = map(
1:nrow(yaxisKey), function(i){
list(label=yaxisKey$label[i], value=yaxisKey$value[i])
}),
value = "gdpPercap"
)
#Create the button
logbutton <- dccRadioItems(
id = 'yaxis-type',
options = list(list(label = 'Linear', value = 'linear'),
list(label = 'Log', value = 'log')),
value = 'linear'
)
graph <- dccGraph(
id = 'gap-graph',
figure=make_plot() # gets initial data using argument defaults
)
####NEW : create the Dash component
graph_country <- dccGraph(
id = 'gap-graph-country',
figure=make_country_graph() # gets initial data using argument defaults
)
sources <- dccMarkdown("[Data Source](https://cran.r-project.org/web/packages/gapminder/README.html)")
## Create Dash instance
app <- Dash$new()
## Specify App layout
app$layout(
htmlDiv(
list(
heading_title,
heading_subtitle,
#selection components
htmlLabel('Select y-axis metric:'),
yaxisDropdown,
htmlIframe(height=15, width=10, style=list(borderWidth = 0)), #space
htmlLabel('Select y scale : '),
logbutton,
#graph
graph,
####NEW : display the plot
graph_country,
htmlIframe(height=20, width=10, style=list(borderWidth = 0)), #space
sources
)
)
)
## App Callbacks
app$callback(
#update figure of gap-graph
output=list(id = 'gap-graph', property='figure'),
#based on values of year, continent, y-axis components
params=list(input(id = 'y-axis', property='value'),
input(id = 'yaxis-type', property='value')),
#this translates your list of params into function arguments
function(yaxis_value, yaxis_scale) {
make_plot(yaxis_value, yaxis_scale)
})
####NEW: updates our second graph using linked interactivity
app$callback(output = list(id = 'gap-graph-country', property = 'figure'),
params = list(input(id='y-axis', property='value'),
# Here's where we check for graph interactions!
input(id='gap-graph', property='clickData')),
function(yaxis_value, clickData) {
# clickData contains $x, $y and $customdata
# you can't access these by gapminder column name!
country_name = clickData$points[[1]]$customdata
make_country_graph(country_name, yaxis_value)
})
## Run app
app$run_server()
# command to add dash app in Rstudio viewer:
# rstudioapi::viewer("http://127.0.0.1:8050")
```
Run this app and play with it. You can notice that the second graph is going to change depending on which point you select on the first graph.
Well, this is it, you just did your first cross-filtering!!
## Part 3: Preview of Layouts in Dash [10 mins]
Here are three examples of what dashboards look like in R once layouts have been applied to them.
These were done by former students:
- [Boston Crime Dashboard](https://group-dash-milestone-4.herokuapp.com)
- [Interactive Movie Dashboard](https://movies214-milestone4.herokuapp.com)
- [Job Analyzer](https://dsci532-milestone4-r-107.herokuapp.com)
Next class, we will explore in detail how to achieve the aesthetics that we need.
In the meantime, feel free to explore one of the layouts from [this repo](https://github.com/matthewconnell/dashr_sample_layouts) created by Matthew as a starting point.
## OPTIONAL Appendix: Another example of a Dash multi-level callback
**Link between a bar chart and a scatter plot**
In this example, we are also going to use the app we created last lecture as a starting point. We are going to add a bar graph above the scatter plot. This bar graph is going to represent the variable the user select from the dropdown menu on the y-axis, and the x-axis is going to be the countries. To make it simpler, we are just going to represent the data from the year 2007 on this graph.
The point of this exercise it to update the scatter plot so that it represents only the country the user is going to select on the bar graph.
![](https://raw.githubusercontent.com/firasm/bits/master/dash_callbacks2.png)
**Step 0 : create the new graph**
The first thing we have to do is to create the bar graph.
```{bar gaph_ex2}
make_bar <- function(yaxis="gdpPercap",
scale = "linear"){
# gets the label matching the column value
y_label <- yaxisKey$label[yaxisKey$value==yaxis]
#filter our data based on the year/continent selections
data <- gapminder %>%
filter(year == 2007)
# make the plot
p <- ggplot(data, aes(x=country, y=!!sym(yaxis))) +
geom_bar(stat='identity') +
xlab("Country") +
ylab(y_label) +
ggtitle(paste0("Change in ", y_label, " Over Countries in 2007 ")) +
theme_bw() +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
if (scale == 'log'){
p <- p + scale_y_continuous(trans='log10')
}
ggplotly(p)
}
```
Let's add it to our original app, and create the corresponding Dash component :
```{app_bar_graph_ex2}
# author: YOUR NAME
# date: THE DATE
"This script is the main file that creates a Dash app for cm108 on the gapminder dataset.
Usage: app.R
"
## Load libraries
library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)
library(dashTable)
library(tidyverse)
library(plotly)
library(gapminder)
## Make plots
####NEW : Create the plot
make_bar <- function(yaxis="gdpPercap",
scale = "linear"){
# gets the label matching the column value
y_label <- yaxisKey$label[yaxisKey$value==yaxis]
#filter our data based on the year/continent selections
data <- gapminder %>%
filter(year == 2007)
# make the plot
p <- ggplot(data, aes(x=country, y=!!sym(yaxis))) +
geom_bar(stat='identity') +
xlab("Country") +
ylab(y_label) +
ggtitle(paste0("Change in ", y_label, " Over Countries in 2007 ")) +
theme_bw() +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
if (scale == 'log'){
p <- p + scale_y_continuous(trans='log10')
}
ggplotly(p)
}
make_plot <- function(yaxis = "gdpPercap",
scale = "linear"){
# gets the label matching the column value
y_label <- yaxisKey$label[yaxisKey$value==yaxis]
#filter our data based on the year/continent selections
data <- gapminder
# make the plot!
p <- ggplot(data, aes(x = year, y = !!sym(yaxis), colour = continent)) +
geom_jitter(alpha = 0.6) +
scale_color_manual(name = 'Continent', values = continent_colors) +
scale_x_continuous(breaks = unique(data$year))+
xlab("Year") +
ylab(y_label) +
ggtitle(paste0("Change in ", y_label, " over time (Scale : ", scale, ")")) +
theme_bw()
if (scale == 'log'){
p <- p + scale_y_continuous(trans='log10')
}
# passing c("text") into tooltip only shows the contents of
ggplotly(p, tooltip = c("text"))
}
## Assign components to variables
heading_title <- htmlH1('Gapminder Dash Demo')
heading_subtitle <- htmlH2('Looking at country data interactively')
# Storing the labels/values as a tibble means we can use this both
# to create the dropdown and convert colnames -> labels when plotting
yaxisKey <- tibble(label = c("GDP Per Capita", "Life Expectancy", "Population"),
value = c("gdpPercap", "lifeExp", "pop"))
#Create the dropdown
yaxisDropdown <- dccDropdown(
id = "y-axis",
options = map(
1:nrow(yaxisKey), function(i){
list(label=yaxisKey$label[i], value=yaxisKey$value[i])
}),
value = "gdpPercap"
)
#Create the button
logbutton <- dccRadioItems(
id = 'yaxis-type',
options = list(list(label = 'Linear', value = 'linear'),
list(label = 'Log', value = 'log')),
value = 'linear'
)
####NEW : add the Dash component that corresponds to the bar graph
graph_bar <- dccGraph(
id = 'gap-graph-bar',
figure=make_bar() # gets initial data using argument defaults
)
graph <- dccGraph(
id = 'gap-graph',
figure=make_plot() # gets initial data using argument defaults
)
sources <- dccMarkdown("[Data Source](https://cran.r-project.org/web/packages/gapminder/README.html)")
## Create Dash instance
app <- Dash$new()
## Specify App layout
app$layout(
htmlDiv(
list(
heading_title,
heading_subtitle,
#selection components
htmlLabel('Select y-axis metric:'),
yaxisDropdown,
htmlIframe(height=15, width=10, style=list(borderWidth = 0)), #space
htmlLabel('Select y scale : '),
logbutton,
#graph
####NEW : Display the bar graph
graph_bar,
graph,
htmlIframe(height=20, width=10, style=list(borderWidth = 0)), #space
sources
)
)
)
## App Callbacks
app$callback(
#update figure of gap-graph
output=list(id = 'gap-graph', property='figure'),
#based on values of year, continent, y-axis components
params=list(input(id = 'y-axis', property='value'),
input(id = 'yaxis-type', property='value')),
#this translates your list of params into function arguments
function(yaxis_value, yaxis_scale) {
make_plot(yaxis_value, yaxis_scale)
})
## Run app
app$run_server()
# command to add dash app in Rstudio viewer:
# rstudioapi::viewer("http://127.0.0.1:8050")
```
Now, if you run this code, you should see two graphs : the scatter plot we had last time, and a bar graph. The scatter plot should be dynamic (it should still change depending on what the user select in the dropdown menu), while the bar graph shouldn't change for now.
Now, let's link the two graphs together!
**Step 1 : specify the action when you click on the first plot**
Try to modify the `make_bar` function so that the name of the country the user selects is saved in the `customdata` argument. Try to also change the way the bar graph looks when the user selects a country (highlight the selected country).
```{make_bar_final_ex2}
make_bar <- function(yaxis="gdpPercap",
scale = "linear"){
# gets the label matching the column value
y_label <- yaxisKey$label[yaxisKey$value==yaxis]
#filter our data based on the year/continent selections
data <- gapminder %>%
filter(year == 2007)
# make the plot
p <- ggplot(data, aes(x=country, y=!!sym(yaxis), customdata=country)) +
geom_bar(stat='identity') +
xlab("Country") +
ylab(y_label) +
ggtitle(paste0("Change in ", y_label, " Over Countries in 2007 ")) +
theme_bw() +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
if (scale == 'log'){
p <- p + scale_y_continuous(trans='log10')
}
ggplotly(p) %>%
layout(clickmode = 'event+select')
}
```
**Step 2 : change the `make_plot` function so that it takes the country as an argument**
We have to add `country` as an argument of the `make_plot` function so that we can plot only the points that correspond to those countries.
```{make_plot_final_ex2}
all_countries <- unique(gapminder$country)
make_plot <- function(yaxis = "gdpPercap",
scale = "linear",
country_selected = all_countries){
# gets the label matching the column value
y_label <- yaxisKey$label[yaxisKey$value==yaxis]
#filter our data based on the year/continent selections
data <- gapminder %>%
filter(country %in% country_selected)
# make the plot!
# NEW: the customdata mapping adds country to the tooltip and allows
# its selection using clickData.
p <- ggplot(data, aes(x = year, y = !!sym(yaxis),
colour = continent)) +
geom_jitter(alpha=0.6) +
scale_color_manual(name = 'Continent', values = continent_colors) +
scale_x_continuous(breaks = unique(data$year))+
xlab("Year") +
ylab(y_label) +
ggtitle(paste0("Change in ", y_label, " over time, country : ", country_selected, " (Scale : ", scale, ")")) +
theme_bw()
if (scale == 'log'){
p <- p + scale_y_continuous(trans='log10')
}
ggplotly(p)
}
```
**Step 3 : create the callback**
It's time to link our two plots. You have two callbacks to do/update.
- The first callback is to update the bar graph depending on the values for the y-axis and the scale for the y-axis the user chose.
- The second callback is to update the scatter plot depending on the values for the y-axis and the scale for the y-axis the user chose from the dropdown menu, and the country the user selected from the bar graph. Be careful, `clickData$points[[1]]$customdata` is going to be `NULL` when the app will load for the first time. If you don't want your scatter plot to be empty when the user opens the page, you have to create a `for` loop to avoid this issue.
```{callback_ex2}
app$callback(
#update figure of gap-graph-bar
output=list(id = 'gap-graph-bar', property='figure'),
#based on values of year, continent, y-axis components
params=list(input(id = 'y-axis', property='value'),
input(id = 'yaxis-type', property='value')),
#this translates your list of params into function arguments
function(yaxis_value, yaxis_scale) {
make_bar(yaxis_value, yaxis_scale)
})
app$callback(output = list(id = 'gap-graph', property = 'figure'),
params = list(input(id='y-axis', property='value'),
input(id = 'yaxis-type', property='value'),
# Here's where we check for graph interactions!
input(id='gap-graph-bar', property='clickData')),
function(yaxis_value, yaxis_scale, clickData) {
# clickData contains $x, $y and $customdata
# you can't access these by gapminder column name!
country_name = clickData$points[[1]]$customdata
if (is.null(country_name)) {
country_name <- unique(gapminder$country)
}
make_plot(yaxis_value, yaxis_scale, country_name)
})
```
**Step 4 : Put it all together**
This is the last step, gather all the chunks of code we created so far, and run the app!
```{final_app_ex2}
# author: YOUR NAME
# date: THE DATE
"This script is the main file that creates a Dash app for cm108 on the gapminder dataset.
Usage: app.R
"
## Load libraries
library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)
library(dashTable)
library(tidyverse)
library(plotly)
library(gapminder)
## Make plot
make_bar <- function(yaxis="gdpPercap",
scale = "linear"){
# gets the label matching the column value
y_label <- yaxisKey$label[yaxisKey$value==yaxis]
#filter our data based on the year/continent selections
data <- gapminder %>%
filter(year == 2007)
# make the plot
p <- ggplot(data, aes(x=country, y=!!sym(yaxis) ,customdata=country)) +
geom_bar(stat='identity') +
xlab("Country") +
ylab(y_label) +
ggtitle(paste0("Change in ", y_label, " Over Countries in 2007 ")) +
theme_bw() +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
if (scale == 'log'){
p <- p + scale_y_continuous(trans='log10')
}
ggplotly(p) %>%
# NEW: this is optional but changes how the graph appears on click
# more layout stuff: https://plotly-r.com/improving-ggplotly.html
layout(clickmode = 'event+select')
}
all_countries <- unique(gapminder$country)
make_plot <- function(yaxis = "gdpPercap",
scale = "linear",
country_selected = all_countries){
# gets the label matching the column value
y_label <- yaxisKey$label[yaxisKey$value==yaxis]
#filter our data based on the year/continent selections
data <- gapminder %>%
filter(country %in% country_selected)
# make the plot!
# NEW: the customdata mapping adds country to the tooltip and allows
# its selection using clickData.
p <- ggplot(data, aes(x = year, y = !!sym(yaxis),
colour = continent)) +
geom_jitter(alpha=0.6) +
scale_color_manual(name = 'Continent', values = continent_colors) +
scale_x_continuous(breaks = unique(data$year))+
xlab("Year") +
ylab(y_label) +
ggtitle(paste0("Change in ", y_label, " over time, country : ", country_selected, " (Scale : ", scale, ")")) +
theme_bw()
if (scale == 'log'){
p <- p + scale_y_continuous(trans='log10')
}
ggplotly(p)
}
## Assign components to variables
heading_title <- htmlH1('Gapminder Dash Demo')
heading_subtitle <- htmlH2('Looking at country data interactively')
# Storing the labels/values as a tibble means we can use this both
# to create the dropdown and convert colnames -> labels when plotting
yaxisKey <- tibble(label = c("GDP Per Capita", "Life Expectancy", "Population"),
value = c("gdpPercap", "lifeExp", "pop"))
#Create the dropdown
yaxisDropdown <- dccDropdown(
id = "y-axis",
options = map(
1:nrow(yaxisKey), function(i){
list(label=yaxisKey$label[i], value=yaxisKey$value[i])
}),
value = "gdpPercap"
)
#Create the button
logbutton <- dccRadioItems(
id = 'yaxis-type',
options = list(list(label = 'Linear', value = 'linear'),
list(label = 'Log', value = 'log')),
value = 'linear'
)
graph <- dccGraph(
id = 'gap-graph',
figure=make_plot() # gets initial data using argument defaults
)
graph_bar <- dccGraph(
id = 'gap-graph-bar',
figure=make_bar() # gets initial data using argument defaults
)
sources <- dccMarkdown("[Data Source](https://cran.r-project.org/web/packages/gapminder/README.html)")
## Create Dash instance
app <- Dash$new(external_stylesheets = "https://codepen.io/chriddyp/pen/bWLwgP.css")
## Specify App layout
app$layout(
htmlDiv(
list(
heading_title,
heading_subtitle,
#selection components
htmlLabel('Select y-axis metric:'),
yaxisDropdown,
htmlIframe(height=15, width=10, style=list(borderWidth = 0)), #space
htmlLabel('Select y scale : '),
logbutton,
#graph
graph_bar,
graph,
htmlIframe(height=20, width=10, style=list(borderWidth = 0)), #space
sources
)
)
)
## App Callbacks
app$callback(
#update figure of gap-graph-bar
output=list(id = 'gap-graph-bar', property='figure'),
#based on values of year, continent, y-axis components