Repository navigation
Expand file tree
/
Copy pathserver.R
More file actions
1608 lines (1428 loc) · 60.9 KB
/
Copy pathserver.R
File metadata and controls
1608 lines (1428 loc) · 60.9 KB
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
# library(shiny)
# Add Google font and enable text rendering
font_add_google("Roboto", "roboto")
showtext_auto()
# For Page 1.2
# Load required data for Page 1.2 (ridgeline plots of boarding and frequency density)
df_combined_sampled <- readRDS("data/page_1.2_story_mode.rds")
# Recode line name for consistent formatting in plots
df_combined_sampled <- df_combined_sampled %>%
mutate(Line_Name = recode(Line_Name,
"Richmond and City Loop" = "Richmond and\nCity Loop"))
# For Page 1.3 Exploration Mode
# Define feature labels used in Page 1.3 for model explanation
label_map <- c(
"Train_Freq" = "Train Frequency",
"Direction_Up_Proportion" = "Up Direction %",
"solar" = "Solar Radiation",
"windspeed" = "Wind Speed",
"relativehumidity" = "Relative Humidity",
"airtemp" = "Air Temperature",
"Day_Type" = "Day Type",
"Day_of_Week" = "Day of Week",
"atmosphericpressure" = "Atmospheric Pressure",
"vapourpressure" = "Vapour Pressure",
"strikes" = "Strike Events",
"winddirection" = "Wind Direction"
)
# Function to apply feature name mapping to improve plot readability
add_feature_labels <- function(df) {
df %>%
mutate(Label = ifelse(Feature %in% names(label_map),
label_map[Feature],
Feature)) # fallback to original name
}
# For Page 2.4 Exploration Mode
# Load precomputed data for Page 2.4 (station-level crowding index)
df_combined <- readRDS("data/page_2.4_explore_mode_precomputed.rds")
# Ensure character format for day type column
df_combined <- df_combined %>%
mutate(Day_Type = as.character(Day_Type))
# Load station metadata and extract coordinates for leaflet mapping
station_meta <- st_read("data/page_2.4_station_stats_with_station_type.geojson") %>%
mutate(
Longitude = st_coordinates(geometry)[,1],
Latitude = st_coordinates(geometry)[,2]
) %>%
st_drop_geometry() %>%
select(Station_Name, N_Metro_Platform, N_Lines, Station_Type, Latitude, Longitude)
# Color palette for crowding index visualization
pal <- colorNumeric(palette = "inferno", domain = df_combined$Crowding_Index, reverse = TRUE)
# The Real Part
# Define server-side logic
# ---- Page 0 Home Page ----
shinyServer(function(input, output, session) {
# Handle navbar tab link clicks from homepage
observeEvent(input$to_page1, {
updateTabsetPanel(session, "main_nav", selected = "Line-Level Analysis")
})
observeEvent(input$to_page2, {
updateTabsetPanel(session, "main_nav", selected = "Station-Level Analysis")
})
observeEvent(input$to_page3, {
updateTabsetPanel(session, "main_nav", selected = "About Project")
})
# ---- Page 1 Line-Level Analysis----
## -------- Page 1.1 --------
### ---- Story Mode ----
# Render static plot for Story Mode showing passenger boardings in both directions
output$page11_story_plot <- renderPlot({
# Load pre-processed dataset for line-level directional boarding
df_boarding_by_line_direction <- readRDS("data/page_1.1_story_mode.rds")
# Reshape data to long format with direction labels and custom colors
df_boarding_long <- df_boarding_by_line_direction %>%
pivot_longer(cols = c("Up", "Down"), names_to = "Direction", values_to = "Boardings") %>%
mutate(
Direction_Label = if_else(Direction == "Up", "Towards Flinders", "From Flinders"),
Color = if_else(Direction == "Up", rgb(0.2, 0.7, 0.1, 0.6), rgb(0.7, 0.2, 0.1, 0.6))
)
# Create label data for annotation on plot
df_boarding_labels <- df_boarding_by_line_direction %>%
mutate(
max_val = pmax(Up, Down), # Take the higher of Up or Down as label reference
label_x = max_val + 250000, # Offset for label positioning
label_y = Line_Name,
label_text = label_number(accuracy = 0.1, scale_cut = cut_short_scale())(sum_load)
)
# Plot: each line shows a directional segment and two colored dots representing boardings
ggplot() +
geom_segment(data = df_boarding_by_line_direction,
aes(x = Line_Name, xend = Line_Name, y = Down, yend = Up),
color = "grey40") +
geom_point(data = df_boarding_long,
aes(x = Line_Name, y = Boardings, color = Direction_Label),
size = 7, shape = 16) +
geom_text(data = df_boarding_labels,
aes(x = label_y, y = label_x, label = label_text),
color = "grey40", size = 5, hjust = 0) +
scale_color_manual(
values = c("Towards Flinders" = rgb(0.2, 0.7, 0.1, 0.6),
"From Flinders" = rgb(0.7, 0.2, 0.1, 0.6)),
name = "Train Line Direction",
guide = guide_legend(override.aes = list(shape = 16, size = 8))
) +
coord_flip() + # Horizontal layout for better readability
scale_y_continuous(
labels = label_number(accuracy = 0.1, scale_cut = cut_short_scale()),
limits = c(NA, max(df_boarding_labels$label_x) * 1.05)
) +
labs(
title = "Train Line Annual Passengers Boarding: Towards vs From Flinders",
x = "Train Line",
y = "Total Number of Passengers Boarding"
) +
theme_minimal(base_family = "roboto") +
theme(
plot.title = element_text(size = 17, face = "bold", color = "#2a475e"),
axis.title = element_text(size = 13, face = "bold"),
legend.title = element_text(size = 13, face = "bold"),
legend.text = element_text(size = 12),
legend.position = "top",
axis.text.x = element_text(size = 12),
axis.text.y = element_text(size = 12)
)
})
### ---- Exploration Mode ----
# Render plot for interactive exploration with day type/time bin filters and sorting option
output$page11_exploration_plot <- renderPlot({
# Load dataset for interactive filtering
df_exploration_input <- readRDS("data/page_1.1_exploration_mode.rds")
# Get user input values
selected_daytype <- input$page11_daytype
selected_timebin <- input$page11_timebin
sort_by_diff <- input$page11_sortbydiff
# Filter data based on selected day type and time bin
df_exploration_filtered <- df_exploration_input %>%
filter(
(selected_daytype == "All" | Day_Type == selected_daytype),
(selected_timebin == "All" | Time_Bin == selected_timebin)
)
# Aggregate across time/day if user selects "All"
if (selected_daytype == "All" | selected_timebin == "All") {
df_exploration_filtered <- df_exploration_filtered %>%
group_by(Line_Name) %>%
summarise(
Up = sum(Up),
Down = sum(Down),
sum_load = sum(sum_load),
diff_load = sum(diff_load),
.groups = "drop"
)
}
# Sort by difference or total, and prepare label text
if (sort_by_diff) {
df_exploration_filtered <- df_exploration_filtered %>%
arrange(desc(-diff_load)) %>%
mutate(
Line_Name = factor(Line_Name, levels = Line_Name),
label_value = diff_load,
label_text = label_number(accuracy = 0.1, scale_cut = cut_si(""))(diff_load)
)
} else {
df_exploration_filtered <- df_exploration_filtered %>%
arrange(desc(-sum_load)) %>%
mutate(
Line_Name = factor(Line_Name, levels = Line_Name),
label_value = sum_load,
label_text = label_number(accuracy = 0.1, scale_cut = cut_si(""))(sum_load)
)
}
# Reshape for plotting each direction (Up/Down)
df_exploration_long <- df_exploration_filtered %>%
select(Line_Name, Up, Down) %>%
pivot_longer(cols = c(Up, Down), names_to = "Direction", values_to = "Boardings") %>%
mutate(
Direction_Label = if_else(Direction == "Up", "Towards Flinders", "From Flinders"),
Color = if_else(Direction == "Up", rgb(0.2, 0.7, 0.1, 0.6), rgb(0.7, 0.2, 0.1, 0.6))
)
# Generate final interactive plot
ggplot() +
geom_segment(data = df_exploration_filtered,
aes(x = Line_Name, xend = Line_Name, y = Down, yend = Up),
color = "grey40") +
geom_point(data = df_exploration_long,
aes(x = Line_Name, y = Boardings, color = Direction_Label),
size = 7, shape = 16) +
geom_text(data = df_exploration_filtered,
aes(x = Line_Name, y = pmax(Up, Down) * 1.1 + 200, label = label_text),
color = "grey40", size = 5, hjust = 0) +
scale_color_manual(
values = c("Towards Flinders" = rgb(0.2, 0.7, 0.1, 0.6),
"From Flinders" = rgb(0.7, 0.2, 0.1, 0.6)),
name = "Train Line Direction",
guide = guide_legend(override.aes = list(shape = 16, size = 8))
) +
coord_flip() + # Flip coordinates for horizontal layout
scale_y_continuous(
labels = label_number(accuracy = 0.1, scale_cut = cut_si("")),
limits = c(NA, max(pmax(df_exploration_filtered$Up, df_exploration_filtered$Down) * 1.15) * 1.05)
) +
labs(
title = "Train Line Annual Passengers Boarding: Towards vs From Flinders",
x = "Train Line",
y = "Number of Passengers"
) +
theme_minimal(base_family = "roboto") +
theme(
plot.title = element_text(size = 17, face = "bold", color = "#2a475e"),
axis.title = element_text(size = 13, face = "bold"),
legend.title = element_text(size = 13, face = "bold"),
legend.text = element_text(size = 12),
legend.position = "top",
axis.text.x = element_text(size = 12),
axis.text.y = element_text(size = 12)
)
})
# Reset UI inputs when "Reset" button is clicked
observeEvent(input$page11_reset, {
updateSelectInput(session, "page11_daytype", selected = "All")
updateSelectInput(session, "page11_timebin", selected = "All")
updateCheckboxInput(session, "page11_sortbydiff", value = FALSE)
})
## ---- Page 1.2 ----
### ---- Story Mode ----
#### ---- Story 1 ----
# Render a density ridge plot showing passenger boarding density over time
# for the top 3 train lines: Pakenham, Lilydale, and Craigieburn.
# Density is weighted by number of boardings.
output$Page12_story1 <- renderPlot({
df_story1 <- df_combined_sampled %>%
filter(Line_Name %in% c("Pakenham", "Lilydale", "Craigieburn"),
Metric == "Passenger Boarding Density")
ggplot(df_story1, aes(x = Arrival_Time_Scheduled, y = Line_Name, fill = Metric, colour = Metric)) +
geom_density_ridges(
aes(
height = ..density..,
weight = Passenger_Boardings,
group = interaction(Line_Name, Metric)
),
alpha = 0.4,
scale = 1.2,
stat = "density"
) +
scale_fill_manual(values = c("Passenger Boarding Density" = "darkorange")) +
scale_colour_manual(values = c("Passenger Boarding Density" = "darkorange")) +
scale_x_time(
labels = scales::label_time(format = "%H:%M"),
breaks = hms::hms(hours = seq(0, 24, by = 4))
) +
labs(
title = "Passenger Boarding Density by Time (Top 3 Lines)",
x = "Time of Day",
y = "Train Line"
) +
theme_minimal(base_family = "roboto") +
theme(
plot.title = element_text(size = 17, face = "bold", color = "#2a475e"),
axis.title = element_text(size = 13, face = "bold"),
legend.position = "none",
axis.text.x = element_text(size = 12),
axis.text.y = element_text(size = 12)
)
})
#### ---- Story 2 ----
# Render a density ridge plot of train frequency over time
# for the same top 3 lines, using uniform weighting.
output$Page12_story2 <- renderPlot({
df_story2 <- df_combined_sampled %>%
filter(Line_Name %in% c("Pakenham", "Lilydale", "Craigieburn"),
Metric == "Train Frequency Density")
ggplot(df_story2, aes(x = Arrival_Time_Scheduled, y = Line_Name, fill = Metric, colour = Metric)) +
geom_density_ridges(
aes(
height = ..density..,
weight = 1,
group = interaction(Line_Name, Metric)
),
alpha = 0.4,
scale = 1.2,
stat = "density"
) +
scale_fill_manual(values = c("Train Frequency Density" = "steelblue")) +
scale_colour_manual(values = c("Train Frequency Density" = "steelblue")) +
scale_x_time(
labels = scales::label_time(format = "%H:%M"),
breaks = hms::hms(hours = seq(0, 24, by = 4))
) +
labs(
title = "Train Frequency Density by Time (Top 3 Lines)",
x = "Time of Day",
y = "Train Line"
) +
theme_minimal(base_family = "roboto") +
theme(
plot.title = element_text(size = 17, face = "bold", color = "#2a475e"),
axis.title = element_text(size = 13, face = "bold"),
legend.position = "none",
axis.text.x = element_text(size = 12),
axis.text.y = element_text(size = 12)
)
})
#### ---- Story 3 ----
# Overlay plot showing both boarding density and train frequency for top 3 lines.
# Highlights the supply-demand relationship.
output$Page12_story3 <- renderPlot({
df_story3 <- df_combined_sampled %>%
filter(Line_Name %in% c("Pakenham", "Lilydale", "Craigieburn"))
ggplot(df_story3, aes(x = Arrival_Time_Scheduled, y = Line_Name, fill = Metric, colour = Metric)) +
geom_density_ridges(
aes(
height = ..density..,
weight = ifelse(Metric == "Passenger Boarding Density", Passenger_Boardings, 1),
group = interaction(Line_Name, Metric)
),
alpha = 0.3,
scale = 1,
stat = "density"
) +
scale_fill_manual(
values = c("Train Frequency Density" = "steelblue", "Passenger Boarding Density" = "darkorange")
) +
scale_colour_manual(
values = c("Train Frequency Density" = "steelblue", "Passenger Boarding Density" = "darkorange")
) +
scale_x_time(
labels = scales::label_time(format = "%H:%M"),
breaks = hms::hms(hours = seq(0, 24, by = 4))
) +
labs(
title = "Supply vs Demand - Top 3 Lines",
x = "Time of Day",
y = "Train Line"
) +
theme_minimal(base_family = "roboto") +
theme(
plot.title = element_text(size = 17, face = "bold", color = "#2a475e"),
axis.title = element_text(size = 13, face = "bold"),
legend.title = element_text(size = 13, face = "bold"),
legend.text = element_text(size = 12),
legend.position = "top",
axis.text.x = element_text(size = 12),
axis.text.y = element_text(size = 12)
)
})
#### ---- Story 4 ----
# Similar overlay plot for two outlier lines: Alamein and Richmond/City Loop.
# Useful for anomaly investigation.
output$Page12_story4 <- renderPlot({
df_story4 <- df_combined_sampled %>%
filter(Line_Name %in% c("Alamein", "Richmond and\nCity Loop"))
ggplot(df_story4, aes(x = Arrival_Time_Scheduled, y = Line_Name, fill = Metric, colour = Metric)) +
geom_density_ridges(
aes(
height = ..density..,
weight = ifelse(Metric == "Passenger Boarding Density", Passenger_Boardings, 1),
group = interaction(Line_Name, Metric)
),
alpha = 0.3,
scale = 1,
stat = "density"
) +
scale_fill_manual(
values = c("Train Frequency Density" = "steelblue", "Passenger Boarding Density" = "darkorange")
) +
scale_colour_manual(
values = c("Train Frequency Density" = "steelblue", "Passenger Boarding Density" = "darkorange")
) +
scale_x_time(
labels = scales::label_time(format = "%H:%M"),
breaks = hms::hms(hours = seq(0, 24, by = 4))
) +
labs(
title = "Supply vs Demand - Anomalous Lines",
x = "Time of Day",
y = "Train Line"
) +
theme_minimal(base_family = "roboto") +
theme(
plot.title = element_text(size = 17, face = "bold", color = "#2a475e"),
axis.title = element_text(size = 13, face = "bold"),
legend.title = element_text(size = 13, face = "bold"),
legend.text = element_text(size = 12),
legend.position = "top",
axis.text.x = element_text(size = 12),
axis.text.y = element_text(size = 12)
)
})
### ---- Exploration Mode ----
# Generalized plot function for dynamic day-type overlay plotting.
# This is reused in the interactive exploration section.
plot_daytype_overlay <- function(df, title_text) {
ggplot(df, aes(x = Arrival_Time_Scheduled, y = Line_Name, fill = Metric, colour = Metric)) +
geom_density_ridges(
aes(
height = ..density..,
weight = ifelse(Metric == "Passenger Boarding Density", Passenger_Boardings, 1),
group = interaction(Line_Name, Metric)
),
alpha = 0.3,
scale = 1,
stat = "density"
) +
scale_fill_manual(
values = c("Train Frequency Density" = "steelblue", "Passenger Boarding Density" = "darkorange")
) +
scale_colour_manual(
values = c("Train Frequency Density" = "steelblue", "Passenger Boarding Density" = "darkorange")
) +
scale_x_time(
labels = scales::label_time(format = "%H:%M"),
breaks = hms::hms(hours = seq(0, 24, by = 4))
) +
labs(
title = title_text,
x = "Time of Day",
y = "Train Line"
) +
theme_minimal(base_family = "roboto") +
theme(
plot.title = element_text(size = 17, face = "bold", color = "#2a475e"),
axis.title = element_text(size = 13, face = "bold"),
legend.title = element_text(size = 13, face = "bold"),
legend.text = element_text(size = 12),
legend.position = "top",
axis.text.x = element_text(size = 12),
axis.text.y = element_text(size = 12)
)
}
# Render the interactive plot based on selected day type.
output$Page12_explorePlot <- renderPlot({
# Retrieve user-selected day type from UI input
selected_type <- input$Page12_daytype
# Load the corresponding dataset based on day type
df <- switch(selected_type,
"All" = readRDS("data/page_1.2_story_mode.rds"),
"Normal Weekday" = readRDS("data/page_1.2_explore_weekday.rds"),
"Normal Weekend" = readRDS("data/page_1.2_explore_weekend.rds"),
"Public Holiday" = readRDS("data/page_1.2_explore_public.rds"),
"School Holiday" = readRDS("data/page_1.2_explore_school.rds"))
# Set dynamic title for plot
title_text <- paste0(selected_type, " - Supply vs Demand")
# Render plot using generalized overlay function
plot_daytype_overlay(df, title_text)
})
## ---- Page 1.3 ----
### ---- Story Mode ----
# Render the bar plot showing the top 10 most important features from the Random Forest model (Story Mode)
output$Page13_rfBarPlot <- renderPlot({
# Load pre-calculated feature importance data from Random Forest
df_rf_importance <- readRDS("data/page_1.3_story_mode.rds")
# Create a bar chart to show feature importance based on two metrics
ggplot(df_rf_importance, aes(x = reorder(Feature, -Mean_Scaled_Importance), y = Scaled_Importance, fill = Metric)) +
geom_bar(stat = "identity", position = position_dodge(width = 0.7)) +
scale_fill_manual(values = c("MSE Increase" = "#1f77b4", "Node Purity Increase" = "#ff7f0e")) +
labs(
title = "Top 10 Features for Predicting Total Passenger Boardings",
x = "Features Used to Predict Total Boardings",
y = "Scaled Importance (0–1)",
fill = "Importance Metric"
) +
theme_minimal(base_family = "roboto") +
theme(
axis.text.x = element_text(size = 12, angle = 45, hjust = 1),
axis.text.y = element_text(size = 12),
axis.title = element_text(size = 13, face = "bold"),
plot.title = element_text(size = 17, face = "bold", color = "#2a475e"),
legend.title = element_text(size = 13, face = "bold"),
legend.text = element_text(size = 12)
)
})
### ---- Exploration Mode ----
# Dynamically render feature importance plot based on selected model type
output$Page13_explore_plot <- renderPlot({
# Ensure model choice input is available
req(input$Page13_model_choice)
# Load the corresponding feature importance data based on selected model
df <- switch(input$Page13_model_choice,
"rf" = readRDS("data/page_1.3_story_mode.rds"),
"dt" = readRDS("data/page_1.3_dt_importance.rds"),
"lm" = readRDS("data/page_1.3_lm_importance.rds"),
"lasso" = readRDS("data/page_1.3_lasso_importance.rds")
)
# If the data includes a 'Metric' column, plot with multiple importance metrics (e.g. for RF)
if ("Metric" %in% colnames(df)) {
ggplot(df, aes(x = reorder(Feature, -Scaled_Importance), y = Scaled_Importance, fill = Metric)) +
geom_bar(stat = "identity", position = position_dodge(width = 0.7)) +
scale_fill_manual(values = c("MSE Increase" = "#1f77b4", "Node Purity Increase" = "#ff7f0e")) +
labs(
title = "Random Forest Feature Importance",
x = "Feature",
y = "Scaled Importance",
fill = "Importance Metric"
) +
theme_minimal(base_family = "roboto") +
theme(
axis.text.x = element_text(size = 12, angle = 45, hjust = 1),
axis.text.y = element_text(size = 12),
axis.title = element_text(size = 12),
plot.title = element_text(size = 16, face = "bold", color = "#2a475e"),
legend.title = element_text(size = 12),
legend.text = element_text(size = 12)
)
} else {
# For models without multiple metrics (e.g. DT, LM, LASSO), use simplified single-metric bar plot
df <- add_feature_labels(df) # Add human-readable feature labels
ggplot(df, aes(x = reorder(Label, -Importance), y = Importance)) +
geom_bar(stat = "identity", fill = "grey60") +
labs(
title = "Model-Based Feature Importance",
x = "Feature",
y = "Importance"
) +
theme_minimal(base_family = "roboto") +
theme(
axis.text.x = element_text(size = 12, angle = 45, hjust = 1),
axis.text.y = element_text(size = 12),
axis.title = element_text(size = 12),
plot.title = element_text(size = 16, face = "bold", color = "#2a475e")
)
}
})
## ---- End of Page 1 ----
# Navigate to next tab when "next_page2" button is clicked
observeEvent(input$next_page2, {
updateTabsetPanel(session, "main_nav", selected = "Station-Level Analysis")
session$sendCustomMessage("scrollToTop", "go")
})
# Navigate back to home tab when "back_home1" button is clicked
observeEvent(input$back_home1, {
updateTabsetPanel(session, "main_nav", selected = "Home")
session$sendCustomMessage("scrollToTop", "go")
})
# ---- Page 2 Station-Level Analysis----
## ---- Page 2.1 ----
### ---- Story Mode 1 ----
output$Page21_story1 <- renderPlot({
# Load and prepare data
df <- read_csv("data/page_2.1_story1.csv") %>%
mutate(Day_Type = factor(Day_Type,
levels = c("Normal Weekday", "Normal Weekend", "Public Holiday", "School Holiday"),
ordered = TRUE
))
# Create label positions and formatting
df_labels <- df %>%
mutate(
label_pct = paste0(round(prop * 100), "%"),
label_pax = paste0(round(Total), " pax"),
x_label = ifelse(Type == "Boardings", x - r * 0.5, x + r * 0.5),
y_label = y,
y_pax = y - r - 0.10
)
# Plot arc bars for each day type and flow type
ggplot(df) +
geom_arc_bar(aes(x0 = x, y0 = y, r0 = 0, r = r, start = start, end = end, fill = Type),
color = "white", size = 0.4, alpha = 0.95
) + # Draw proportional arc segments
scale_fill_manual(values = c("Boardings" = "steelblue", "Alightings" = "darkorange")) + # Custom fill colors for types
scale_x_continuous(
breaks = 1:4,
labels = levels(df$Day_Type),
expand = expansion(mult = 0.1)
) +
coord_fixed() +
labs(x = NULL, y = NULL, title = "Passenger Flow Composition by Day Type", fill = "Flow Type") +
theme_minimal(base_family = "roboto") +
theme(
axis.text.y = element_blank(),
axis.text.x = element_text(size = 12),
legend.title = element_text(size = 13, face = "bold"),
legend.text = element_text(size = 12),
plot.title = ggtext::element_textbox_simple(size = 17, face = "bold", color = "#2a475e", margin = margin(b = 20, unit = "pt"))
) +
geom_text(data = df_labels, aes(x = x_label, y = y_label, label = label_pct), size = 4, color = "white") + # Add % labels inside arcs
geom_text(data = df_labels %>% distinct(Day_Type, x, y_pax, label_pax),
aes(x = x, y = y_pax, label = label_pax), size = 4, color = "gray40"
) # Add total passenger labels below arcs
})
### ---- Story Mode 2 ----
output$Page21_story2 <- renderPlot({
# Load and prepare time-binned passenger flow data
df <- read_csv("data/page_2.1_story2.csv") %>%
mutate(
Time_Bin = factor(Time_Bin, levels = c("00:00–04:00", "04:00–08:00", "08:00–12:00", "12:00–16:00", "16:00–20:00", "20:00–00:00")),
r_raw = sqrt(Total) / sqrt(max(Total)) * 0.45,
r = pmax(r_raw, 0.25)
)
# Generate label positions for arcs
df_labels <- df %>%
mutate(
label_pct = paste0(round(prop * 100), "%"), # Percentage labels
label_pax = paste0(round(Total), " pax"), # Total labels
x_label = ifelse(Type == "Boardings", x + r * 0.5, x - r * 0.5),
y_label = y,
y_pax = y - r - 0.2
)
# Plot arc bars by time bins
ggplot(df) +
geom_arc_bar(aes(x0 = x, y0 = y, r0 = 0, r = r, start = start, end = end, fill = Type),
color = "white", size = 0.4, alpha = 0.95
) +
scale_fill_manual(values = c("Boardings" = "steelblue", "Alightings" = "darkorange")) +
scale_x_continuous(
breaks = 1:6,
labels = levels(df$Time_Bin),
expand = expansion(mult = 0.1)
) +
coord_fixed() +
labs(x = NULL, y = NULL, title = "Passenger Flow Composition by Time of Day", fill = "Flow Type") +
theme_minimal(base_family = "roboto") +
theme(
axis.text.y = element_blank(),
axis.text.x = element_text(size = 12),
legend.title = element_text(size = 13, face = "bold"),
legend.text = element_text(size = 12),
plot.title = ggtext::element_textbox_simple(size = 17, face = "bold", color = "#2a475e", margin = margin(b = 20, unit = "pt"))
) +
geom_text(data = df_labels, aes(x = x_label, y = y_label, label = label_pct), size = 4, color = "white") + # Add % labels
geom_text(data = df_labels %>% distinct(Time_Bin, x, y_pax, label_pax), # Add total pax labels
aes(x = x, y = y_pax, label = label_pax), size = 4, color = "gray40"
) +
scale_x_continuous(
breaks = 1:6,
labels = levels(df$Time_Bin),
expand = c(0, 0)
) # Override x-axis expansion
})
### ---- Story Mode 3 ----
output$Page21_story3 <- renderPlot({
# Read and prepare grid data with categorical order
df <- read_csv("data/page_2.1_story3_story4.csv") %>%
mutate(
Day_Type = factor(Day_Type, levels = c("Normal Weekday", "Normal Weekend", "Public Holiday", "School Holiday"), ordered = TRUE),
Time_Bin = factor(Time_Bin, levels = c("00:00–04:00", "04:00–08:00", "08:00–12:00", "12:00–16:00", "16:00–20:00", "20:00–00:00"))
) %>%
mutate(x = as.numeric(Time_Bin), y = as.numeric(fct_rev(Day_Type)))
# Reshape to long format and compute arc angles
df_long <- df %>%
pivot_longer(cols = c(Boardings, Alightings), names_to = "Type", values_to = "Value") %>%
group_by(Day_Type, Time_Bin) %>%
mutate(prop = Value / sum(Value), start = cumsum(lag(prop, default = 0)) * 2 * pi, end = cumsum(prop) * 2 * pi) %>%
ungroup() %>%
mutate(x = as.numeric(Time_Bin), y = as.numeric(fct_rev(Day_Type)))
# Plot grid of circular flows
ggplot(df_long) +
geom_arc_bar(aes(x0 = x, y0 = y, r0 = 0, r = r, start = start, end = end, fill = Type),
color = "white", size = 0.3, alpha = 0.9
) +
scale_fill_manual(values = c("Boardings" = "steelblue", "Alightings" = "darkorange")) +
scale_x_continuous(breaks = 1:6, labels = levels(df$Time_Bin), expand = expansion(mult = 0.1)) +
scale_y_continuous(breaks = 1:4, labels = rev(levels(df$Day_Type)), expand = expansion(mult = 0.1)) +
labs(x = "Time of Day", y = "Day Type", fill = "Flow Type", title = "Hourly Station Passenger Volume Composition by Day Type and Time of Day") +
theme_minimal(base_family = "roboto") +
theme(
plot.title = element_text(size = 17, face = "bold", color = "#2a475e"),
axis.title = element_text(size = 13, face = "bold"),
legend.title = element_text(size = 13, face = "bold"),
legend.text = element_text(size = 12),
axis.text.x = element_text(size = 12),
axis.text.y = element_text(size = 12)
) +
geom_text(
data = df, aes(x = as.numeric(Time_Bin), y = as.numeric(fct_rev(Day_Type)) - r - 0.075, label = paste0(round(100 * Boardings / Total), "%")),
color = "steelblue", size = 3.2
) + # Boarding % inside arcs
geom_text(
data = df, aes(x = as.numeric(Time_Bin), y = as.numeric(fct_rev(Day_Type)) - r - 0.18, label = paste0(round(Total), " pax")),
color = "gray40", size = 3.2
) + # Total below arcs
annotate("rect", xmin = 4.5, xmax = 5.5, ymin = 3.4, ymax = 4.4, alpha = 0.1, color = "#2a475e", fill = "#2a475e") + # Highlight specific regions
annotate("rect", xmin = 0.6, xmax = 1.4, ymin = 1.6, ymax = 2.2, alpha = 0.1, color = "#2a475e", fill = "#2a475e")
})
### ---- Story Mode 4 ----
output$Page21_story4 <- renderPlot({
# Similar setup as Story 3
df <- read_csv("data/page_2.1_story3_story4.csv") %>%
mutate(
Day_Type = factor(Day_Type, levels = c("Normal Weekday", "Normal Weekend", "Public Holiday", "School Holiday"), ordered = TRUE),
Time_Bin = factor(Time_Bin, levels = c("00:00–04:00", "04:00–08:00", "08:00–12:00", "12:00–16:00", "16:00–20:00", "20:00–00:00"))
) %>%
mutate(x = as.numeric(Time_Bin), y = as.numeric(fct_rev(Day_Type)))
df_long <- df %>%
pivot_longer(cols = c(Boardings, Alightings), names_to = "Type", values_to = "Value") %>%
group_by(Day_Type, Time_Bin) %>%
mutate(prop = Value / sum(Value), start = cumsum(lag(prop, default = 0)) * 2 * pi, end = cumsum(prop) * 2 * pi) %>%
ungroup() %>%
mutate(x = as.numeric(Time_Bin), y = as.numeric(fct_rev(Day_Type)))
ggplot(df_long) +
geom_arc_bar(aes(x0 = x, y0 = y, r0 = 0, r = r, start = start, end = end, fill = Type),
color = "white", size = 0.3, alpha = 0.9
) +
scale_fill_manual(values = c("Boardings" = "steelblue", "Alightings" = "darkorange")) +
scale_x_continuous(breaks = 1:6, labels = levels(df$Time_Bin), expand = expansion(mult = 0.1)) +
scale_y_continuous(breaks = 1:4, labels = rev(levels(df$Day_Type)), expand = expansion(mult = 0.1)) +
labs(x = "Time of Day", y = "Day Type", fill = "Flow Type", title = "Hourly Station Passenger Volume Composition by Day Type and Time of Day") +
theme_minimal(base_family = "roboto") +
theme(
plot.title = element_text(size = 17, face = "bold", color = "#2a475e"),
axis.title = element_text(size = 13, face = "bold"),
legend.title = element_text(size = 13, face = "bold"),
legend.text = element_text(size = 12),
axis.text.x = element_text(size = 12),
axis.text.y = element_text(size = 12)
) +
geom_text(
data = df, aes(x = as.numeric(Time_Bin), y = as.numeric(fct_rev(Day_Type)) - r - 0.075, label = paste0(round(100 * Boardings / Total), "%")),
color = "steelblue", size = 3.2
) +
geom_text(
data = df, aes(x = as.numeric(Time_Bin), y = as.numeric(fct_rev(Day_Type)) - r - 0.18, label = paste0(round(Total), " pax")),
color = "gray40", size = 3.2
) +
annotate("rect", xmin = 0.6, xmax = 3.4, ymin = 1.5, ymax = 4.4, alpha = 0.1, color = "#2a475e", fill = "#2a475e")
})
### ---- Exploration Mode ----
# Load exploration data with station-wise breakdown
df_explore_21 <- read_csv("data/page_2.1_exploration_mode.csv") %>%
mutate(
Day_Type = factor(
Day_Type,
levels = c("Normal Weekday", "Normal Weekend", "Public Holiday", "School Holiday"),
ordered = TRUE
),
Time_Bin = factor(
Time_Bin,
levels = c('00:00–04:00', '04:00–08:00', '08:00–12:00',
'12:00–16:00', '16:00–20:00', '20:00–00:00')
)
)
# Update station selection dynamically
observe({
updateSelectInput(
inputId = "Page21_stationSelect",
choices = unique(df_explore_21$Station_Name),
selected = unique(df_explore_21$Station_Name)[1]
)
})
# Reactive filtered data
df_selected_station <- reactive({
req(input$Page21_stationSelect)
# Filter data for chosen station and calculate radii
df_filtered <- df_explore_21 %>%
filter(Station_Name == input$Page21_stationSelect) %>%
mutate(
Total = Boardings + Alightings,
r = sqrt(Total) / sqrt(max(Total)) * 0.35
)
# Reshape and compute arc geometry
df_long <- df_filtered %>%
pivot_longer(cols = c(Boardings, Alightings), names_to = "Type", values_to = "Value") %>%
group_by(Day_Type, Time_Bin) %>%
mutate(
prop = Value / sum(Value),
start = cumsum(lag(prop, default = 0)) * 2 * pi,
end = cumsum(prop) * 2 * pi,
mid = (start + end) / 2
) %>%
ungroup() %>%
mutate(
x = as.numeric(Time_Bin),
y = as.numeric(fct_rev(Day_Type))
)
list(df = df_filtered, df_long = df_long)
})
# Plot selected station's data
output$Page21_explorePlot <- renderPlot({
df_data <- df_selected_station()
df <- df_data$df
df_long <- df_data$df_long
ggplot(df_long) +
geom_arc_bar(aes(x0 = x, y0 = y, r0 = 0, r = r,
start = start, end = end, fill = Type),
color = "white", size = 0.3, alpha = 0.9) +
scale_fill_manual(values = c("Boardings" = "steelblue", "Alightings" = "darkorange")) +
scale_x_continuous(breaks = 1:6, labels = levels(df$Time_Bin), expand = expansion(mult = 0.1)) +
scale_y_continuous(breaks = 1:4, labels = rev(levels(df$Day_Type)), expand = expansion(mult = 0.1)) +
labs(
x = "Time of Day", y = "Day Type", fill = "Flow Type",
title = paste("Hourly Passenger Volume Composition at", input$Page21_stationSelect, "Station")
) +
theme_minimal(base_family = "roboto") +
theme(
plot.title = element_text(size = 17, face = "bold", color = "#2a475e"),
axis.title = element_text(size = 13, face = "bold"),
legend.title = element_text(size = 13, face = "bold"),
legend.text = element_text(size = 12),
axis.text.x = element_text(size = 12),
axis.text.y = element_text(size = 12)
) +
geom_text(
data = df,
aes(x = as.numeric(Time_Bin),
y = as.numeric(fct_rev(Day_Type)) - r - 0.075,
label = paste0(round(100 * Boardings / (Boardings + Alightings)), "%")),
color = "steelblue", size = 3.2
) +
geom_text(
data = df,
aes(x = as.numeric(Time_Bin),
y = as.numeric(fct_rev(Day_Type)) - r - 0.18,
label = paste0(round(Boardings + Alightings), " pax")),
color = "gray40", size = 3.2
)
})
## ---- Page 2.2 ----
# Render a chord diagram showing OD (Origin-Destination) passenger flows
output$Page22_cityloopChord <- renderChorddiag({
# Load OD matrix CSV file
od_df <- read.csv("data/page_2.2_cityloop_od_matrix.csv", row.names = 1, check.names = FALSE)
# Trim whitespace in column and row names
colnames(od_df) <- trimws(colnames(od_df))
rownames(od_df) <- trimws(rownames(od_df))
# Convert to matrix format
od_matrix <- as.matrix(od_df)
# Fix station order to ensure consistent visual layout
custom_order <- c("Flagstaff", "Southern Cross", "Melbourne Central", "Parliament", "Richmond", "Flinders Street")
od_matrix <- od_matrix[custom_order, custom_order]
# Generate chord diagram with styling options
chorddiag(od_matrix,
palette = "Set3",
tooltipUnit = " people",
tickInterval = 200000,
ticklabelFontsize = 8,
groupnameFontsize = 15,
groupnamePadding = 10,
margin = 80)
})
## ---- Page 2.3 ----
### ---- Story Mode ----
# Render radar chart for the top 3 crowded stations
output$Page23_top3Radar <- renderPlot({
# Add Google font and enable text rendering
# font_add_google("Roboto", "roboto")
# showtext_auto()
# Load station stats from geojson
Station_Stats <- st_read("data/page_2.3_2.4_station_stats.geojson", quiet = TRUE)
# Select top 3 stations with highest crowding index
top3 <- Station_Stats %>%
arrange(desc(Crowding_Index)) %>%
slice(1:3) %>%
st_drop_geometry() %>%
select(
Station_Name,
`Peak Hour Volume` = norm_peak_volume,
`Passenger Volume\nper Platform` = norm_per_platform_volume,
`Train Count per Platform` = norm_per_platform_trains,
`Passenger Volume\nper Train` = norm_per_train_volume
)
# Normalize values for radar chart and rename group
radar_data <- top3 %>%
mutate(across(-Station_Name, rescale)) %>%
rename(group = Station_Name)
# Generate radar chart using ggradar
plt <- radar_data %>%
ggradar(
font.radar = "roboto",
grid.label.size = 5,
axis.label.size = 5,
group.point.size = 3,
group.line.width = 1.8,
group.colours = c("#F8766D", "#FDCB6E", "#00B894"),
fill.alpha = 0.25
) +
labs(title = "Top 3 Stations' SCI Dimensions") +
coord_equal(clip = "off") +
theme(
text = element_text(family = "roboto"),
plot.title.position = "plot",
plot.title = element_textbox_simple(
size = 20,
face = "bold",
color = "#2a475e",
hjust = 0,
margin = margin(l = -42, unit = "pt"),
width = unit(1, "npc")
),
legend.position = c(1.1, 0),
legend.justification = c(1, 0),
legend.text = element_text(size = 15, family = "roboto"),
legend.key = element_rect(fill = NA, color = NA),
legend.background = element_blank()
)
# Print radar plot
print(plt)
})
### ---- Exploration Mode ----
# Load and preprocess station stats (no geometry)
station_stats_data <- st_read("data/page_2.3_2.4_station_stats.geojson", quiet = TRUE) %>%
st_drop_geometry()
# Extract list of all station names
all_stations <- station_stats_data$Station_Name
# Determine the median station by crowding index
median_station_name <- station_stats_data %>%
arrange(Crowding_Index) %>%
slice(ceiling(n() / 2)) %>%
pull(Station_Name)
# Initialize select input with station names