-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfunctions.R
executable file
·1160 lines (1027 loc) · 37.5 KB
/
functions.R
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
# Function to show spinner when loading charts/tables
# Parameter: whats_loading:
# e.g. plotlyOutput("multi_indicator_chart", height = "33em")
loading <- function(whats_loading){
withSpinner(whats_loading, type = 5, color = "#3F3685", size = 0.5)
}
# Function to read in data and split by measure, remove redundant columns
load_and_split_dataframe <- function(measure) {
data <- filter(runchart_dataframe, measure == {{measure}}) %>%
janitor::remove_empty(which = c("cols"), quiet = TRUE)
return(data)
}
# Function to create empty plot when no data available
# Parameters:
# height_plot: height of the empty chart in pixels
# text_nodata: What text will show when no data is available
plot_nodata <- function(height_plot = 450, text_nodata) {
text_na <- list(align = "centre",
text = text_nodata,
xref = "x",
yref = "y",
showarrow = FALSE,
name = "_no_data_plot_marker_") # so can check later if plot object has no data
plot_ly(height = height_plot) %>%
add_trace(x = 0,
y = 0,
visible = FALSE,
type = "scatter",
mode = "lines") %>%
layout(annotations = text_na,
#empty layout
yaxis = list(showline = FALSE,
showticklabels = FALSE,
showgrid = FALSE,
fixedrange = TRUE),
xaxis = list(showline = FALSE,
showticklabels = FALSE,
showgrid = FALSE,
fixedrange = TRUE),
font = list(size = 14)) %>%
config(displayModeBar = FALSE) # taking out plotly logo and collaborate button
}
# function to make the sidebar menu accessible (https://www.jumpingrivers.com/blog/accessible-shiny-standards-wcag/)
# modified because it was causing a lag in the inputId updating (caused problems with filters)
# now there is no lag but it doesn't initialise with the value 'home' - have queried this witn jumping rivers
accessible_menu = function(bad_menu) {
tab_input = tags$script(
"
function customMenuHandleClick(e) {
let n = $(e.currentTarget).find('a')[0].dataset.value;
doSomethingWith(n);
}
function doSomethingWith(val) {
Shiny.setInputValue('topics', val);
}
$(document).ready(
function() {
$('ul.sidebar-menu li').click(customMenuHandleClick)
});
"
)
bad_menu$children[[length(bad_menu$children)]] = NULL
real_menu = tagList(bad_menu, tab_input)
real_menu
}
# removes aria label from left-hand menu icon "fas fa-angles-right" to satisfy accessibility check
rem_aria_label <- function(icon) {
icon[["attribs"]][["aria-label"]] = NULL
return(icon)
}
# removes aria label from expanded (right-hand) menu icon "fas fa-angle-left pull-right" to satisfy accessibility check
rem_menu_aria_label <- function(menu) {
menu[["children"]][[1]][["children"]][[3]][["attribs"]][["aria-label"]] = NULL
return(menu)
}
# removes aria label from icon "fas fa-plus" "fas fa-minus" and adds title to "button" to satisfy accessibility check
rem_button_aria_label <- function(box) {
box[["children"]][[1]][["children"]][[1]][["children"]][[2]][["children"]][[1]][["children"]][[1]][["attribs"]][["aria-label"]] = NULL
box[["children"]][[1]][["children"]][[1]][["children"]][[2]][["children"]][[1]][["attribs"]][["title"]] = "open and close button"
return(box)
}
# Function to create the small multiple charts with a blue median line
# Parameters:
# plotdata: dataframe with data to be plotted
# measure_value: variable to be plotted as black dots/lines
# hover: hovertext for the measure_value
# centreline: variable to be plotted as a solid blue line
# dottedline: variable to be plotted as a dotted blue line
# yaxislabel: text to appear on y axis
# This function is not as up-to-date as the next one as it was deemed not required
creates_overview_charts_with_median <- function(plotdata,
measure_value,
hover = "mytext",
centreline = "median",
dottedline = "extended",
yaxislabel = yaxislabel){
y_max <- max(plotdata$measure_value)
xaxis_plots <- orig_xaxis_plots
xaxis_plots[["showticklabels"]] <- if_else(plotdata$hbname %in% island_names, TRUE, FALSE)
xaxis_plots[["dtick"]] <- case_when(plotdata$period == "Q" ~ "2",
TRUE ~ "M6")
yaxis_plots <- orig_yaxis_plots
yaxis_plots[["range"]] <- list(-1.0, y_max * 1.05)
# annotations - plots a single blue dot at 10 weeks on last data point for
# AVERAGE GESTATION AT BOOKING only
a <- list(
x = max(plotdata$date),
y = 10,
xanchor = 'left',
yanchor = 'middle',
text = " 10 weeks",
font = list(family = 'Arial',
size = 14,
color = phs_colours("phs-blue")),
showarrow = FALSE
)
if(first(plotdata$measure) == "GESTATION AT BOOKING"){
overview <- plotdata %>%
split(.$hbname2) %>%
lapply(
function(d)
plot_ly(
d,
x = ~ date,
y = ~ get(centreline), # solid blue line
type = "scatter",
mode = "lines",
line = list(color = phs_colours("phs-blue"),
width = 1),
hovertext = ""
) %>%
add_trace(
y = ~ get(dottedline), # dotted blue line
type = "scatter",
mode = "lines",
line = list(
color = phs_colours("phs-blue"),
width = 1,
dash = "4"
),
hovertext = ""
) %>%
add_trace(
y = ~ measure_value,
type = "scatter",
mode = "lines+markers",
line = list(color = "black", # black lines
width = 1),
marker = list(color = "black", # black dots
size = 5),
hovertext = ~ get(hover),
hoverinfo = "text"
) %>%
add_trace(
x = ~ max(plotdata$date),
y = 10,
type = 'scatter',
mode = "lines+markers", # dot for 10 weeks
line = list(opacity = 0),
marker = list(color = phs_colours("phs-blue"),
size = 5),
hovertext = ""
) %>%
add_trace(
data = filter(gest_at_booking_small_multiples_data,!is.na(new_median)),
y = ~ NEW_MEDIAN, # green line (where applicable)
type = "scatter",
mode = "lines",
line = list(
color = phs_colours("phs-green"),
width = 1
),
marker = NULL,
name = ~ paste0(case_when(
hbname == "NHS Tayside" ~
paste0(hbname, " average from Aug 2020 to end Dec 2020"),
hbname == "NHS Forth Valley" ~
paste0(hbname, " average from Mar 2021 to end Jun 2021"),
TRUE ~ ""
)
),
legendrank = 400,
hovertext = ""
) %>%
add_trace(
data = filter(gest_at_booking_small_multiples_data,!is.na(new_extended)),
y = ~ new_extended, # dotted green line (where applicable)
type = "scatter",
mode = "lines",
line = list(
color = phs_colours("phs-green"),
width = 1,
dash = "4"
),
marker = NULL,
name = ~ paste0(case_when(
hbname == "NHS Tayside" ~
paste0(hbname, " projected average from Jan 2021"),
hbname == "NHS Forth Valley" ~
paste0(hbname, " projected average from Jul 2021"),
TRUE ~ ""
)
),
legendrank = 500,
hovertext = ""
) %>%
layout(annotations = a) %>%
layout(
#font = list(size = 12),
xaxis = xaxis_plots,
yaxis = yaxis_plots,
showlegend = FALSE,
annotations = list(
x = 0.5,
y = 1.0,
text = ~ unique(hbname2),
xref = "paper",
yref = "paper",
xanchor = "center",
yanchor = "bottom",
showarrow = FALSE
)
)
)
} else {
overview <- plotdata %>%
split(.$hbname2) %>%
lapply(
function(d)
plot_ly(
d,
x = ~ date,
y = ~ get(centreline), # solid blue line
type = "scatter",
mode = "lines",
line = list(color = phs_colours("phs-blue"),
width = 1),
hovertext = ""
) %>%
add_trace(
y = ~ get(dottedline), # dotted blue line
type = "scatter",
mode = "lines",
line = list(
color = phs_colours("phs-blue"),
width = 1,
dash = "4"
),
hovertext = ""
) %>%
add_trace(
y = ~ measure_value,
type = "scatter",
mode = "lines+markers",
line = list(color = "black", # black dots
width = 1),
marker = list(color = "black", # black lines
size = 5),
hovertext = ~ get(hover),
hoverinfo = "text"
) %>%
layout(
#font = list(size = 12),
xaxis = xaxis_plots,
yaxis = yaxis_plots,
showlegend = FALSE,
annotations = list(
x = 0.5,
y = 1.0,
text = ~ unique(hbname2),
xref = "paper",
yref = "paper",
xanchor = "center",
yanchor = "bottom",
showarrow = FALSE
)
)
)
}
overview <- overview %>%
subplot(nrows = 5,
heights = c(0.15, 0.2, 0.2, 0.2, 0.18),
margin = c(0.01, 0.01, 0.05, 0.02),
shareX = TRUE,
shareY = TRUE) %>%
layout(
annotations = list(
x = 0,
y = 0.5,
text = ~ yaxislabel,
xshift = -50,
textangle = 270,
showarrow = FALSE,
xref = "paper",
yref = "paper"
),
margin = list(pad = 10) # distance between axis and plot
) %>%
config(displaylogo = F, displayModeBar = FALSE)
return(overview)
}
# Function to create the small multiple charts without a blue median line
# Parameters:
# plotdata: dataframe with data to be plotted
# measure_value: variable to be plotted as black dots/lines
# hover: hovertext for the measure_value
# yaxislabel: text to appear on y axis
creates_small_multiple_charts_without_median <- function(plotdata,
measure_value,
hover = "mytext"){
# sorts plots in correct order (Scotland first)
# average gestation at termination has hbname2 defined already, the other measures have
# hbname2 defined here
if(!"hbname2" %in% names(plotdata)) {
plotdata$hbname2 <- factor(plotdata$hbname, levels = HBnames)
}
plotdata <- droplevels(plotdata) # drop unused factor levels
y_max <- max(plotdata$y_max) # allows a range to be set for y-axis
# sets y-axis label
yaxislabeltext <- case_match(
first(plotdata$measure),
"GESTATION AT BOOKING" ~ "Average gestation at booking (weeks)",
"GESTATION AT TERMINATION" ~ paste(strwrap("Average gestation at termination (weeks)",
width = 25),
collapse = "\n"),
"TEARS" ~ "Percentage of women (%)",
"APGAR5" ~ "Percentage of babies (%)",
.default = "Percentage of births (%)"
)
# sets whether y-axis label should be shown (prevents double-printing)
yaxislabelswitch <- if_else(
(first(plotdata$measure) == "GESTATION AT TERMINATION" | first(plotdata$hbgroup) == "mainland"),
yaxislabeltext, "")
# sets where y-axis label should be positioned
yaxislabelposition <- if_else(
first(plotdata$measure) == "GESTATION AT TERMINATION",
0.5, 0.4)
xaxis_plots <- orig_xaxis_plots
# xaxis_plots[["range"]] <- range(unique(plotdata$date))
xaxis_plots[["dtick"]] <- case_when(plotdata$period == "Q" ~ "3",
TRUE ~ "M6") # frequency of tick marks on x-axis
# remove x-axis ticklabels from "mainland" charts except for Average Gestation at Termination
xaxis_plots[["showticklabels"]] <- if_else(
first(plotdata$hbgroup) == "mainland" && first(plotdata$measure != "GESTATION AT TERMINATION"),
FALSE, TRUE)
yaxis_plots <- orig_yaxis_plots
yaxis_plots[["title"]] <- list(standoff = 10)
yaxis_plots[["tickmode"]] <- "auto"
yaxis_plots[["range"]] <- list(0, y_max * 1.05) # expands the y-axis range to prevent cut-offs
plot_heights = if(first(plotdata$hbgroup) == "mainland") {
c(0.2, 0.25, 0.25, 0.2)} else {0.75}
if(first(plotdata$measure) == "GESTATION AT BOOKING") { # adds annotation at 10 weeks, no markers
# annotations - plots a single blue dot at 10 weeks on last data point for
# AVERAGE GESTATION AT BOOKING only
a <- list(
x = max(plotdata$date) + months(1),
y = 11.9,
xref ="x",
yref = "y",
xanchor = 'right',
yanchor = 'middle',
text = "10 weeks ",
font = list(family = 'Arial',
size = 12,
color = phs_colours("phs-blue")),
showarrow = FALSE
)
overview <- plotdata %>%
split(.$hbname2) %>%
lapply(
function(d)
plot_ly(
d,
x = ~ date
) %>%
add_lines(
y = ~ measure_value,
line = list(color = "black", # black lines
width = 1),
hovertext = ~ get(hover),
hoverinfo = "text",
color = I("black"),
showlegend = FALSE,
) %>%
add_markers(
x = ~ max(plotdata$date) + months(1),
y = 10,
marker = list(color = phs_colours("phs-blue"),
size = 6),
hoverinfo = "none",
showlegend = FALSE
) %>%
layout(annotations = a) %>%
layout(
font = plotly_global_font,
xaxis = xaxis_plots,
yaxis = yaxis_plots,
#plot_bgcolor='#ecebf3',
annotations = list( # HB names
x = 0.5,
y = 1.0,
text = ~ unique(hbname2),
xref = "paper",
yref = "paper",
xanchor = "center",
yanchor = "bottom",
showarrow = FALSE
),
margin = list(pad = 10) # distance between axis and plot
)
)
} else if(first(plotdata$measure) == "GESTATION AT TERMINATION") { # no markers
overview <- plotdata %>%
split(.$hbname2) %>%
lapply(
function(d)
plot_ly(
d,
x = ~ date,
y = ~ measure_value,
type = "scatter",
mode = "lines+markers",
line = list(color = "black", # black lines
width = 1),
marker = list(opacity = 0),
hovertext = ~ get(hover),
hoverinfo = "text",
color = I("black")
) %>%
layout(
font = plotly_global_font,
xaxis = xaxis_plots,
yaxis = yaxis_plots,
#plot_bgcolor='#ecebf3',
showlegend = FALSE,
annotations = list( # HB names
x = 0.5,
y = 1.0,
text = ~ unique(hbname2),
xref = "paper",
yref = "paper",
xanchor = "center",
yanchor = "bottom",
showarrow = FALSE
),
margin = list(pad = 10) # distance between axis and plot
)
)
} else {
overview <- plotdata %>%
split(.$hbname2) %>%
lapply(
function(d)
plot_ly(
d,
x = ~ date,
y = ~ measure_value,
type = "scatter",
mode = "lines+markers",
line = list(color = "black", # black lines
width = 1),
marker = list(color = "black", # black dots
size = 5),
hovertext = ~ get(hover),
hoverinfo = "text",
color = I("black")
) %>%
layout(
font = plotly_global_font,
xaxis = xaxis_plots,
yaxis = yaxis_plots,
#plot_bgcolor='#ecebf3',
showlegend = FALSE,
annotations = list( # HB names
x = 0.5,
y = 1.0,
text = ~ unique(hbname2),
xref = "paper",
yref = "paper",
xanchor = "center",
yanchor = "bottom",
showarrow = FALSE
),
margin = list(pad = 10) # distance between axis and plot
)
)
}
overview <- overview %>%
subplot(nrows = if_else(first(plotdata$hbgroup) == "mainland", 4, 1),
heights = plot_heights,
margin = c(0.01, 0.01, 0.05, 0.05), # gives more room between plots
shareX = TRUE,
shareY = TRUE) %>%
layout(annotations = list(text = ~ yaxislabelswitch,
font = list(size = 14),
x = 0,
y = ~ yaxislabelposition,
xshift = -60,
textangle = 270,
showarrow = FALSE,
xref = "paper",
yref = "paper"
)
) %>%
config(displaylogo = F, displayModeBar = FALSE)
return(overview)
}
# Function to run the small multiples charts code (for layout)
# Parameters:
# plotdata: dataframe with data to be plotted
# calls creates_small_multiple_charts_without_median
# produces either one chart or two charts in a list (GESTATION AT TERMINATION)
subplot_mainland_island_small_multiples <- function(plotdata) {
if(first(plotdata$measure != "GESTATION AT TERMINATION")) {
small_multiple_subplot <-
plotdata %>%
split(.$hbgroup) %>%
map(\(df) creates_small_multiple_charts_without_median(df)) %>%
subplot(nrows = 2, heights = c(0.8, 0.2), margin = c(0.01, 0.01, 0.05, 0.01)) # seems to give
# separation between mainland and island plots
} else {
small_multiple_subplot <-
plotdata %>%
split(.$hbgroup) %>%
map(\(df) creates_small_multiple_charts_without_median(df))
}
return(small_multiple_subplot)
}
# Function to create the runcharts/timeseries charts
# Parameters:
# plotdata: dataframe with data to be plotted
# measure_value: variable to be plotted as black dots/lines
# hover: hovertext for the measure_value
# centreline: variable to be plotted as a solid blue line
# dottedline: variable to be plotted as a dotted blue line
# trend: green squares for 5 or more points going up or going down
# shift: orange circles for 6 or more points above or below the median
# yaxislabel: text to appear on y axis
creates_runcharts <- function(plotdata,
measure_value,
hover = "mytext",
centreline = "pre_pandemic_median",
dottedline = "extended_pre_pandemic_median",
yaxislabel = "Percentage of births (%)"){
plotdata <- droplevels(plotdata) # drop unused factor levels
y_max <- case_when(
first(plotdata$measure) %in% c("TYPE OF BIRTH", "GESTATION AT BIRTH", "ADMISSIONS TO NEOCARE BY LEVEL OF CARE") ~ 1,
.default = max(plotdata$measure_value, na.rm = TRUE)
)
# include_legend = TRUE for ONE of multiple runcharts (otherwise the legends get repeated)
# and TRUE for single runcharts
include_legend <- case_when(
first(plotdata$measure) == "TYPE OF BIRTH" &
first(plotdata$measure_cat) != "spontaneous vaginal births" ~ FALSE,
first(plotdata$measure) == "GESTATION AT BIRTH" &
first(plotdata$measure_cat) != "between 32 and 36 weeks (inclusive)" ~ FALSE,
first(plotdata$measure) == "ADMISSIONS TO NEOCARE BY LEVEL OF CARE" &
first(plotdata$measure_cat) != "special care" ~ FALSE,
.default = TRUE)
# include_trend_shift_legend = FALSE ensures that the shift and trend legends are switched off
include_trend_shift_legend <- case_when(
first(plotdata$measure) %in% c("BOOKINGS", "TERMINATIONS", "MEDIAN CORRECTED GEST AGE", "ADMISSIONS TO NEOCARE BY LEVEL OF CARE") ~ FALSE,
.default = include_legend)
select_date_tickvals <- switch( # tells plotly where ticks will show
first(plotdata$measure),
"BOOKINGS" = bookings_date_tickvals,
"GESTATION AT BOOKING" = bookings_date_tickvals,
"TERMINATIONS" = terminations_date_tickvals,
"GESTATION AT TERMINATION" = terminations_date_tickvals,
"INDUCTIONS" = SMR02_date_tickvals,
"TYPE OF BIRTH" = SMR02_multiples_date_tickvals,
"TEARS" = SMR02_date_tickvals,
"GESTATION AT BIRTH" = SMR02_multiples_date_tickvals,
"APGAR5" = SMR02_date_tickvals,
"MEDIAN CORRECTED GEST AGE" = SMR02_date_tickvals,
"ADMISSIONS TO NEOCARE BY LEVEL OF CARE" = NeoCare_date_tickvals
)
select_date_ticktext <- switch( # tells plotly what text to show on ticks
first(plotdata$measure),
"BOOKINGS" = bookings_date_ticktext,
"GESTATION AT BOOKING" = bookings_date_ticktext,
"TERMINATIONS" = terminations_date_ticktext,
"GESTATION AT TERMINATION" = terminations_date_ticktext,
"INDUCTIONS" = SMR02_date_ticktext,
"TYPE OF BIRTH" = SMR02_multiples_date_ticktext,
"TEARS" = SMR02_date_ticktext,
"GESTATION AT BIRTH" = SMR02_multiples_date_ticktext,
"APGAR5" = SMR02_date_ticktext,
"MEDIAN CORRECTED GEST AGE" = SMR02_date_ticktext,
"ADMISSIONS TO NEOCARE BY LEVEL OF CARE" = NeoCare_date_ticktext
)
# adds an asterisk to these Board names when there is a related footnote to show
legend_board_name <- if_else(
(first(plotdata$measure == "TYPE OF BIRTH") &
first(plotdata$hbname == "NHS Borders")
) |
# (first(plotdata$measure == "GESTATION AT BOOKING") & # retired as of October 2024 release
# first(plotdata$hbname %in% c("NHS Forth Valley", "NHS Tayside"))
# ) |
(first(plotdata$measure == "GESTATION AT TERMINATION") &
first(plotdata$hbname == "NHS Orkney, NHS Shetland and NHS Western Isles")
),
paste0(first(plotdata$hbname), "*"),
first(plotdata$hbname)
)
legend_name <- case_match(
first(plotdata$measure),
"TYPE OF BIRTH" ~ "percentage of births (%)",
"GESTATION AT BIRTH" ~ "percentage of births (%)",
"ADMISSIONS TO NEOCARE BY LEVEL OF CARE" ~ "percentage of babies (%)",
.default = str_to_lower(var_label(plotdata$measure_value))
)
hoverinfo_format <- switch( # tells plotly how to format median hoverinfo
first(plotdata$measure),
"BOOKINGS" = ",.0f",
"GESTATION AT BOOKING" = ".1f",
"TERMINATIONS" = ",.0f",
"GESTATION AT TERMINATION" = ".1f",
"INDUCTIONS" = ".1f",
"TYPE OF BIRTH" = ".1f",
"TEARS" = ".2f",
"GESTATION AT BIRTH" = ".2f",
"APGAR5" = ".2f",
"MEDIAN CORRECTED GEST AGE" = ".1f",
"ADMISSIONS TO NEOCARE BY LEVEL OF CARE" = ".1f"
)
xaxis_plots <- orig_xaxis_plots
xaxis_plots[["tickmode"]] <- "array"
xaxis_plots[["tickvals"]] <- select_date_tickvals
xaxis_plots[["ticktext"]] <- select_date_ticktext
yaxis_plots <- orig_yaxis_plots
yaxis_plots[["title"]] <- list(text = yaxislabel, standoff = 10)
yaxis_plots[["tickformat"]] <-
if_else(first(plotdata$measure) %in% c("APGAR5", "TEARS"),
".1f",
",d")
yaxis_plots[["range"]] <- list(0, y_max * 1.05) # expands the y-axis range to prevent cut-offs
runcharts <-
plot_ly(
data = plotdata,
x = ~ date,
y = ~ trend, # green trend line needs to be plotted first or it obliterates the others
type = "scatter",
mode = "lines",
line = list(
color = "lightgreen",
width = 10
),
name = orig_trend_label,
legendgroup = "trend",
legendrank = 1200,
showlegend = ~ FALSE,
hovertext = "",
hoverinfo = "none"
) %>%
add_trace(
y = ~ measure_value,
mode = "lines+markers",
line = list(
color = "black", # black lines
width = 1),
marker = list(
color = "black", # black dots
size = 5),
name = legend_name,
legendgroup = "measure_value",
legendrank = 100,
showlegend = ~ include_legend,
hovertext = ~ mytext,
hoverinfo = "text"
) %>%
add_trace(
y = ~ shift, # orange lines
mode = "lines",
line = list(
color = "orange", # orange lines (prevents missing data warning)
width = 2),
name = orig_shift_label,
legendgroup = "shift",
legendrank = 1300,
showlegend = ~ FALSE,
hovertext = "",
hoverinfo = "none"
) %>%
add_trace(
x = ~ min(date), # fake trend to show legend even when no trend exists on chart
y = ~ 0,
mode = "lines",
line = list(
color = "lightgreen",
width = 10
),
name = orig_trend_label, # retrieves label of variable
legendgroup = "trend",
legendrank = 800,
showlegend = ~ include_trend_shift_legend,
hovertext = "",
hoverinfo = "none"
) %>%
add_trace(
x = ~ max(date), # fake shift to show legend even when no shift exists on chart
y = ~ 0,
mode = "lines",
line = list(
color = "orange", # orange lines (prevents missing data warning)
width = 2),
name = orig_shift_label, # retrieves label of variable
legendgroup = "shift",
legendrank = 900,
showlegend = ~ include_trend_shift_legend,
hovertext = "",
hoverinfo = "none"
)
# add medians where plotted
if(first(plotdata$dataset != "NeoCareIn+")) {
runcharts <- runcharts %>%
add_trace(
y = ~ get(centreline), # solid blue line
mode = "lines",
line = list(
color = phs_colours("phs-blue"),
width = 1),
name = ~ paste0(var_label(get(centreline))), # retrieves label of variable
legendgroup = "pre_pandemic_median",
legendrank = 200,
showlegend = ~ include_legend,
hoverinfo = "y",
yhoverformat = hoverinfo_format
) %>%
add_trace(
y = ~ get(dottedline), # dotted blue line
mode = "lines",
line = list(
color = phs_colours("phs-blue"),
width = 1,
dash = "4"
),
name = ~ paste0(var_label(get(dottedline))), # retrieves label of variable
legendgroup = "extended_pre_pandemic_median",
legendrank = 300,
showlegend = ~ include_legend,
hoverinfo = "y",
yhoverformat = hoverinfo_format
)
}
runcharts <- runcharts %>%
layout(
font = plotly_global_font,
xaxis = xaxis_plots,
yaxis = yaxis_plots,
legend = list(title = list(text = paste0(legend_board_name, "<br>")),
tracegroupgap = 15,
orientation = "v",
x = 1.0,
y = 0.5,
xref = "paper",
yref = "paper",
xanchor = "left",
itemclick = FALSE),
margin = list(pad = 10) # distance between axis and plot
) %>%
config(displaylogo = F, displayModeBar = FALSE)
# post-pandemic traces for the GESTATION AT BOOKING and GESTATION AT TERMINATION measures
if(first(plotdata$measure) %in% c("GESTATION AT BOOKING", "GESTATION AT TERMINATION")) {
runcharts <- runcharts %>%
add_trace(
data = filter(plotdata,!is.na(post_pandemic_median)),
y = ~ post_pandemic_median, # magenta line
type = "scatter",
mode = "lines",
line = list(
color = phs_colours("phs-magenta"),
width = 1
),
name = ~ paste0(var_label(post_pandemic_median)
),
legendrank = 600,
showlegend = ~ include_legend,
legendgroup = "post-pandemic median",
hoverinfo = "y",
yhoverformat = hoverinfo_format
) %>%
add_trace(
data = filter(plotdata,!is.na(extended_post_pandemic_median)),
y = ~ extended_post_pandemic_median, # dotted magenta line
type = "scatter",
mode = "lines",
line = list(
color = phs_colours("phs-magenta"),
width = 1,
dash = "4"
),
name = ~ paste0(var_label(extended_post_pandemic_median)
),
legendrank = 700,
showlegend = ~ include_legend,
legendgroup = "extended post-pandemic median",
hoverinfo = "y",
yhoverformat = hoverinfo_format
)
}
# additional traces for the "special" Boards in GESTATION AT BOOKING measure
if(first(plotdata$measure) == "GESTATION AT BOOKING" &
first(plotdata$hbname) %in% c("NHS Forth Valley", "NHS Tayside")) {
runcharts <- runcharts %>%
add_trace(
data = filter(plotdata,!is.na(revised_median)),
y = ~ revised_median, # green line
type = "scatter",
mode = "lines",
line = list(
color = phs_colours("phs-green"),
width = 1
),
name = ~ case_when(
hbname == "NHS Forth Valley" ~
paste0("average gestation from Mar 2021", "<br>", "to end Feb 2022"),
hbname == "NHS Tayside" ~
paste0("average gestation from Aug 2020", "<br>", "to end Jul 2021"),
TRUE ~ ""
),
legendrank = 400,
showlegend = ~ include_legend,
legendgroup = "revised median",
hoverinfo = "y",
yhoverformat = hoverinfo_format
) %>%
add_trace(
data = filter(plotdata,!is.na(extended_revised_median)),
y = ~ extended_revised_median, # dotted green line
type = "scatter",
mode = "lines",
line = list(
color = phs_colours("phs-green"),
width = 1,
dash = "4"
),
name = ~ paste0(case_when(
hbname == "NHS Forth Valley" ~
paste0("projected average gestation from Mar 2022", "<br>", "to end Jun 2022"),
hbname == "NHS Tayside" ~
paste0("projected average gestation from Aug 2021", "<br>", "to end Jun 2022"),
TRUE ~ ""
)
),
legendrank = 500,
showlegend = ~ include_legend,
legendgroup = "extended_revised_median",
hoverinfo = "y",
yhoverformat = hoverinfo_format
)
}
# add plot titles to the multiple runcharts
if(first(plotdata$measure) %in% c("TYPE OF BIRTH", "GESTATION AT BIRTH", "ADMISSIONS TO NEOCARE BY LEVEL OF CARE")) {
runcharts <- runcharts %>%
layout(annotations = list(
x = 0,
y = 1,
text = ~ if_else(
first(plotdata$measure) == "ADMISSIONS TO NEOCARE BY LEVEL OF CARE",
first(plotdata$measure_cat),
first(plotdata$measure_cat_label)
),
font = list(size = 16),
xref = "paper",
yref = "paper",
xanchor = "left",
yanchor = "bottom",
showarrow = FALSE
))
}
return(runcharts)
}
# Function to create the context charts (overall numbers relevant to the measure)
# Parameters:
# plotdata: dataframe with data to be plotted
# date: name of the "date" variable (may be "QUARTER" rather than "date")
# num: main measure variable to be plotted as line (e.g. number of Apgar5 scores < 7)
# num_hover: hovertext for the num
# den: "total" measure variable to be plotted as a line (e.g. the total number of Apgar5 scores recorded)
# den_hover: hovertext for the den
# yaxislabel: text to appear on y axis
creates_context_charts <- function(plotdata,
date,
num,
num_hover = "mytext1",
den,
den_hover = "mytext2",
yaxislabel = "Number of births"){
plotdata <- droplevels(plotdata) # drop unused factor levels