This repository was archived by the owner on Sep 7, 2020. It is now read-only.
forked from Public-Health-Scotland/DRHS_Data_Trend
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.R
More file actions
1055 lines (894 loc) · 37.7 KB
/
Copy pathapp.R
File metadata and controls
1055 lines (894 loc) · 37.7 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
#Name: Drug Related Hospital Statistics (DRHS) Data trend page
#Author: Mike Smith
#Created: 24/01/2019
#Type: Data visualisation
#Written on: RStudio
#Written for: R version 3.5.1
#Output: Shiny application
#Descripion: The Data Trend page is a one-page shiny app that is intended to give a high
#level overview of data at at the level of Scotland, health boards or Alcohol and
#Drug Partnerships (ADP's). It is intended to mirror some of the functionality
#of the current transformed publications data trend page.
#There will be three charts in total in the data trend page
# - 1) Rates of Activity Measure (Stays/Patients/New Patients)
# - 2) Rates of Stays broken down by substance categories
# - 3) Rates of Patients broken down by Demographic measure (Age/Sex/Deprivation).
#There will be intitially three options to choose from
# - 1) Hospital/Clinical Type
# - 2) Geography Type
# = 3) Geography
#A fourth option will be used to 'toggle' between Age, Sex and SIMD for the
#demographic charts.
library(shiny)
library(dplyr)
library(plotly)
library(shinyWidgets)
library(forcats)
library(DT)
library(stringr)
library(shinyBS)
library(bsplus)
##############################################.
############## Data Input ----
##############################################.
#The current data is stored on the stats server in the SubstanceMisuse1 directory
#Current approach to reading in data is to take the SPSS output and then cut it down to
#size and then save as csv files for use.
#Data to be used for explorer and trend pages
all_data<- readRDS("s06-temp09_num_rate_perc_r-shiny_rounded.RDS")
#need to rename the final column as value
all_data<-all_data %>%
rename("value" = value_Round)
#round the data to nearest two
all_data <- all_data %>% mutate(value = round(value, 2))
#We will manually change the names of factors in R until we have an agreed
#terminology for the hospital and clinical types.
all_data<-all_data %>%
mutate(hospital_type= fct_recode(hospital_type,
"General acute"= "General acute (SMR01)",
"Psychiatric" ="Psychiatric (SMR04)",
"Combined gen acute/psych" = "Combined (General acute/Psychiatric)"))
all_data<-all_data %>%
mutate(clinical_type= fct_recode(clinical_type,
"Mental & behavioural (M&B)" = "Mental and Behavioural",
"Overdose (OD)" = "Overdose",
"Combined M&B/OD" = "Combined (Mental and Behavioural/Overdose)"))
activity_summary<-all_data %>%
filter(drug_type == "All",
age_group == "All",
sex == "All",
simd == "All",
measure == "Rate")
activity_summary<-activity_summary %>%
mutate(activity_type= fct_relevel(activity_type,rev))
#filter by drug type
drug_types<- as.character(unique(all_data$drug_type)[2:7])
drug_summary<- all_data %>%
filter(activity_type == "Stays",
drug_type %in% drug_types,
age_group == "All",
sex == "All",
simd == "All",
measure == "Rate") %>%
droplevels()
#filter by demography
demographic_summary<- all_data %>%
filter(drug_type == "All",
activity_type =="Patients",
((age_group != "All" & sex == "All" & simd =="All")|
(age_group == "All" & sex != "All" & simd =="All")|
(age_group == "All" & sex == "All" & simd !="All")),
measure == "Rate")
demographic_summary <- demographic_summary %>%
mutate(sex= fct_relevel(sex,rev))
#we will also set user input options
hospital_types <- as.character(unique(activity_summary$hospital_type))
hospital_types<-c(hospital_types[3],hospital_types[1],hospital_types[2])
clinical_types <- as.character(unique(activity_summary$clinical_type))
clinical_types<-c(clinical_types[3],clinical_types[1],clinical_types[2])
locations <- as.character(unique(activity_summary$geography))
location_types<-list("Scotland" = locations[1],
"NHS Board of residence" = locations[2:15],
"ADP of residence" = locations[16:46])
demographic_types<-c("Age","Sex", "Deprivation")
#Colour blind friendly colour scheme - consult documentation
#Beginning of script
{
##############################################.
############## User Interface ----
##############################################.
ui <- fluidPage(style = "width: 100%; height: 100%; max-width: 1200px;",
titlePanel(title=div(img(src="ISD_NSS_logos.png",height = 96,
width = 223,
style = "float:right;"),
h1("Drug-Related Hospital Statistics"),
h4("Drug and Alcohol Misuse"),
style = "height:96px;"),
windowTitle = "Drug-Related Hospital Statistics"),
tabPanel(title = "",
style = "height: 95%; width: 95%; background-color: #FFFFFF;
border: 0px solid #FFFFFF;",
h1(tags$b("Trend data"), id= 'Top'),
p(
"The Trend data page provides an overview of drug-related hospital stays
in Scotland over time, based on the following charts:
",
tags$ul(
tags$li(tags$a(href= '#activity_link',tags$b("Activity type")),
" (stay rates, patient rates and new patient rates)"),
tags$li(tags$a(href = '#drugs_link',
tags$b("Drug type"))),
tags$li(tags$a(href='#demographics_link', tags$b("Patient demographics")),
" (Age/Sex/Deprivation - choose between these using the blue
buttons above the chart)")
)),
bs_accordion(id = "drhs_text") %>%
bs_set_opts(panel_type = "primary") %>%
bs_append(title = "data selection",
content = p("The charts can be modified using the drop down boxes: ",
tags$ul(
tags$li("Hospital type: general acute or psychiatric hospital data
(or a combination);"),
tags$li("Clinical type: mental & behavioural stays, accidental
poisoning/overdose stays (or a combination); and,"),
tags$li("Location: data from Scotland, specific NHS Boards or
Alcohol and Drug Partnerships.")
)))%>%
bs_append(title = "Chart functions",
content = p("At the top-right corner of each chart, you will see
a toolbar with four buttons: ",
tags$ul(
tags$li(
icon("camera"),
tags$b("Download plot as a png"),
" - save an image of the chart (not available in
Internet Explorer)."
),
tags$li(
icon("search"),
tags$b("Zoom"),
" - click and drag within the chart area to focus
on a specific part."
),
tags$li(
icon("move", lib = "glyphicon"),
tags$b("Pan"),
" - click and move the mouse in any direction to
modify the chart axes."
),
tags$li(
icon("home"),
tags$b("Reset axes"),
" - click this button to return the axes to their
default range."
)
),
"Categories can be shown/hidden by clicking on labels
in the legend to the right of each chart."))%>%
bs_append(title = "Table functions",
content = p("To view your data selection in a table, use the
'Show/hide table' button below each chart.",
tags$ul(
tags$li(
icon("sort", lib = "glyphicon"),
tags$b("Sort"),
" - click to sort a table in ascending or descending
order based on the values in a column. "
),
tags$li(
tags$b("Page controls"),
" - switch to specific page of data within a table. "
)
),
"Categories can be shown/hidden by clicking on labels
in the legend to the right of each chart."))
,
p(
HTML(paste0('A more detailed breakdown of these data is available in the <b> <a href="https://scotland.shinyapps.io/nhs-drhs-data-explorer/">Data explorer</a></b>.'))
) ,
p(
"If you experience any problems using this dashboard or have further
questions relating to the data, please contact us at:",
HTML(paste0('<b> <a href="mailto:NSS.isdsubstancemisuse@nhs.net">NSS.isdsubstancemisuse@nhs.net</a></b>.'))
),
p(
tags$b(
"Note: Statistical disclosure control has been applied to protect
patient confidentiality. Therefore, the figures presented here
may not be additive and may differ from previous publications"
)
),
downloadButton(outputId = "download_glossary",
label = "Download glossary",
class = "glossary"),
tags$head(
tags$style(".glossary { background-color: #0072B2; }
.glossary { color: #FFFFFF; }")
),
p(""),
wellPanel(
tags$style(
".well { background-color: #FFFFFF;
border: 0px solid #336699; }"
),
#Insert the reactive filters. As location is dependent on
#location type this part has to be set up in the server as a
#reactive object and then placed into the UI.
column(
4,
shinyWidgets::pickerInput(
inputId = "Hospital_Type",
label = "Hospital type",
choices = hospital_types
)
),
column(
4,
shinyWidgets::pickerInput(
inputId = "Clinical_Type",
label = "Clinical type",
choices = clinical_types
)
),
column(
4,
shinyWidgets::pickerInput(
inputId = "Location",
label = "Location",
choices = location_types,
options = list(size=5,
`live-search`=TRUE)
)
)
),
#In the main panel of the summary tab, insert the first plot
br(),
br(),
h3("Activity type",id = 'activity_link'),
br(),
mainPanel(
width = 12,
plotlyOutput("activity_summary_plot",
width = "1090px",
height = "600px"),
HTML("<button data-toggle = 'collapse' href = '#activitysummary'
class = 'btn btn-primary' id = 'activitysummary_link'>
<strong> Show/hide table </strong></button>"),
HTML("<div id = 'activitysummary' class = 'collapse'>"),
br(),
dataTableOutput("activity_summary_table"),
HTML("</div>"),
br(),
br()
),
tags$head(
tags$style(HTML("hr {border: 1px solid #000000;}"))
),
p(
br(),
p("Main points (Scotland)",
tags$ul(
tags$li("Over the past 20 years, there was a fourfold increase in the
rate of drug-related general acute hospital stays within Scotland
(from 51 to 199 stays per 100,000 population), with a sharper
increase observed in recent years."),
tags$li("After a lengthy period of stability, the rate of drug-related
psychiatric stays within Scotland increased from 29 to 40 stays per 100,000
population between 2014/15 and 2016/17, before decreasing slightly
in 2017/18 (38)."),
tags$li("In 2017/18, 4,851 patients (90 new patients per 100,000 population)
were treated in hospital (general acute/psychiatric combined) for
drug misuse for the first time within Scotland. The drug-related new patient rate
has increased since 2006/07 (55 new patients per 100,000 population).")
)),
tags$a(href = '#Top',
icon("circle-arrow-up", lib= "glyphicon"),"Back to top"),
hr()
),
h3("Drug type", id= 'drugs_link'),
br(),
br(),
#then insert the drugs plot
mainPanel(
width = 12,
plotlyOutput("drugs_plot",
width = "1090px",
height = "600px"),
HTML("<button data-toggle = 'collapse' href = '#drugs'
class = 'btn btn-primary' id = 'drugs_link'>
<strong> Show/hide table </strong></button>"),
HTML("<div id = 'drugs' class = 'collapse'>"),
br(),
dataTableOutput("drugs_table"),
HTML("</div>"),
br(),
br()
),
p(
br(),
p("Main points (Scotland)",
tags$ul(
tags$li("In 2017/18, 58% of drug-related general acute stays within
Scotland were due
to opioids (drugs similar to heroin)."),
tags$li("51% of drug-related psychiatric stays within Scotland were
associated with ‘multiple/other’ drugs (including
hallucinogens, volatile solvents, multiple drug use and use of
other psychoactive substances (e.g. ecstasy)).")
)),
tags$a(href = '#Top',
icon("circle-arrow-up", lib= "glyphicon"),"Back to top"),
hr()
),
p(
h3("Demographics", id= 'demographics_link')
),
#Insert demographic options
#This part to be converted into toggle button
column(
width = 5,
shinyWidgets::radioGroupButtons(
inputId = "summary_demographic",
label = "Show: ",
choices = demographic_types,
status = "primary",justified = TRUE,
checkIcon = list(yes = icon("ok", lib = "glyphicon")),
selected = "Age"
)
),
#then final demographic plot
mainPanel(
width = 12,
plotlyOutput("demographic_plot",
width = "1090px",
height = "600px"),
HTML("<button data-toggle = 'collapse' href = '#demographic'
class = 'btn btn-primary' id = 'demographic_link'>
<strong> Show/hide table </strong></button>"),
HTML("<div id = 'demographic' class = 'collapse'>"),
br(),
dataTableOutput("demographic_table"),
HTML("</div>"),
br(),
p(
br(),
p("Main points (Scotland)",
tags$ul(
tags$li("Drug-related hospital stays among individuals aged 35 and over
increased over the time series. For general acute stays among
45-54 year olds, there was a greater than seventeen-fold increase
from 12 to 208 patients per 100,000 population between 1996/97
and 2017/18."),
tags$li("Between 1996/97 and 2017/18, drug-related patient rates
for males were approximately twice as high as
female patient rates."),
tags$li("In 2017/18, approximately half of patients with general
acute or psychiatric stays in relation to drug misuse lived
in the 20% most deprived areas in Scotland.")
),
tags$a(href = '#Top',
icon("circle-arrow-up", lib= "glyphicon"),"Back to top")
))
)
#End of UI part
)
)
##############################################.
############## Server ----
##############################################.
#Beginning of server
server <- function(input, output)
{
#Graph information text output
output$text_output<-renderUI({
p(HTML("Show/hide table - show data in a table below the chart."),
p(HTML("At the top-right corner of the chart,
you will see a toolbar with four buttons:"),
br(),
tags$ul(
tags$li(
icon("camera"),
tags$b("Download plot as a png"),
" - click this button to save the graph as an image
(please note that Internet Explorer does not support this
function)."
),
tags$li(
icon("search"),
tags$b("Zoom"),
" - zoom into the graph by clicking this button and then
clicking and dragging your mouse over the area of the
graph you are interested in."
),
tags$li(
icon("move", lib = "glyphicon"),
tags$b("Pan"),
" - adjust the axes of the graph by clicking this button
and then clicking and moving your mouse in any direction
you want."
),
tags$li(
icon("home"),
tags$b("Reset axes"),
" - click this button to return the axes to their
default range."
)
),
HTML("Categories can be shown/hidden by clicking on labels
in the legend to the right of each chart.")
))
})
#we can then plot the graph based on the user input.
#First we create a subset of the data based on user input
#For the activity summary
activity_summary_new <- reactive({
activity_summary %>%
filter(
hospital_type %in% input$Hospital_Type
& clinical_type %in% input$Clinical_Type
& geography %in% input$Location
)%>%
select(year,hospital_type, clinical_type, activity_type,geography,value)
})
#for the substances summary
drug_summary_new <- reactive({
drug_summary %>%
filter(
hospital_type %in% input$Hospital_Type
& clinical_type %in% input$Clinical_Type
& geography %in% input$Location
)%>%
select(year,hospital_type,clinical_type,drug_type,geography,value)
})
#for the demographic summary
#as this is based on two files (and on two separate columns in one
#file) then an if/else function is employed to select the correct data
demographic_summary_new <- reactive({
if (input$summary_demographic == "Age")
{
demographic_summary %>%
filter(
hospital_type %in% input$Hospital_Type
& clinical_type %in% input$Clinical_Type
& geography %in% input$Location
& age_group != "All"
)%>%
select(year,hospital_type,clinical_type,geography,age_group,value)%>%
droplevels()
}
else if(input$summary_demographic == "Sex")
{demographic_summary %>%
filter(
hospital_type %in% input$Hospital_Type
& clinical_type %in% input$Clinical_Type
& geography %in% input$Location
& sex != "All"
) %>%
select(year,hospital_type,clinical_type,geography,sex,value)%>%
droplevels()
}
else if (input$summary_demographic == "Deprivation")
{
demographic_summary %>%
filter(hospital_type %in% input$Hospital_Type
& clinical_type %in% input$Clinical_Type
& geography %in% input$Location
& simd != "All"
)%>%
select(year,hospital_type,clinical_type,geography,simd,value)%>%
droplevels()
}
})
#Then we can plot the actual graph, with labels
#Activity Summary plot
#Tooltip for graphs.
output$activity_summary_plot <- renderPlotly({
#first the tooltip label
tooltip_summary <- paste0(
"Activity type: ",
activity_summary_new()$activity_type,
"<br>",
"Financial year: ",
activity_summary_new()$year,
"<br>",
"Rate: ",
formatC(activity_summary_new()$value, big.mark = ",",digits = 2,format = 'f')
)
#Create the main body of the chart.
plot_ly(
data = activity_summary_new(),
#plot
x = ~ year,
y = ~ value,
color = ~ activity_type,
colors = c('#006ddb','#920000','#004949'),
#tooltip
text = tooltip_summary,
hoverinfo = "text",
#type
type = 'scatter',
mode = 'lines+markers',
marker = list(size = 8),
width = 1000,
height = 600
) %>%
#add in title to chart
layout(title = list(text=
paste0( input$Hospital_Type,
" hospital rates by activity type (",
input$Location,
"; ",
word(input$Clinical_Type,start = 1,sep = " \\("),
")"),
font = list(size = 15)),
separators = ".",
annotations =
list(x = 1.0, y = -0.25,
text = paste0("Source: Drug-Related","<br>",
"Hospital Statistics,","<br>",
"ISD Scotland (",format(Sys.Date(), "%Y"),")"),
showarrow = F, xref='paper', yref='paper',
xanchor='left', yanchor='auto', xshift=0, yshift=0,
font=list(family = "arial", size=12, color="#7f7f7f")),
yaxis = list(
exponentformat = "none",
separatethousands = TRUE,
range = c(0, max(activity_summary_new()$value, na.rm = TRUE) +
(max(activity_summary_new()$value, na.rm = TRUE)
* 10 / 100)),
title = paste0(c(
rep(" ", 20),
"EASR per 100,000 population",
rep(" ", 20),
rep("\n ", 3)
),
collapse = ""),
showline = TRUE,
ticks = "outside"
),
#Set the tick angle to minus 45. It's the only way for the x...
#axis tick labels (fin. years) to display without overlapping...
#with each other.
#Wrap the x axis title in blank spaces so that it doesn't...
#overlap with the x axis tick labels.
xaxis = list(range = c(-1,22),
tickangle = -45,
title = paste0(c(rep(" ", 20),
"<br>",
"Financial year",
rep(" ", 20),
rep("\n ", 3)),
collapse = ""),
showline = TRUE,
ticks = "outside"),
#Fix the margins so that the graph and axis titles have enough...
#room to display nicely.
#Set the font sizes.
margin = list(l = 90, r = 60, b = 160, t = 90),
font = list(size = 13),
#insert legend
showlegend = TRUE,
legend = list(bgcolor = 'rgba(255, 255, 255, 0)',
bordercolor = 'rgba(255, 255, 255, 0)')) %>%
#Remove unnecessary buttons from the modebar.
config(displayModeBar = TRUE,
modeBarButtonsToRemove = list('select2d', 'lasso2d', 'zoomIn2d',
'zoomOut2d', 'autoScale2d',
'toggleSpikelines',
'hoverCompareCartesian',
'hoverClosestCartesian'),
displaylogo = F, editable = F)
})
#Insert table
output$activity_summary_table <- renderDataTable({
datatable(activity_summary_new(),
colnames = c("Financial year",
"Hospital type",
"Clinical type",
"Activity type",
"Location",
"Rate"),
rownames = FALSE,
style = "Bootstrap",
options = list(searching= FALSE,
lengthChange= FALSE)
)%>%
formatRound(columns = 6,digits = 2)
})
# Substances Plot
#Again start with the tooltip summary
output$drugs_plot <- renderPlotly({
#first the tooltip label
tooltip_summary <- paste0(
"Drug type: ",
drug_summary_new()$drug_type,
"<br>",
"Financial year: ",
drug_summary_new()$year,
"<br>",
"Rate: ",
formatC(drug_summary_new()$value, big.mark = ",",
digits = 2,format = 'f')
)
#Create the main body of the chart.
plot_ly(
data = drug_summary_new(),
#plot
x = ~ year,
y = ~ value,
color = ~ drug_type,
colors = ~ c(
'#004949',
'#db6d00',
'#ffb6db',
'#006ddb',
'#920000',
'#b66dff'
),
#tooltip
text = tooltip_summary,
hoverinfo = "text",
#type
type = 'scatter',
mode = 'lines+markers',
marker = list(size = 8),
width = 1000,
height = 600
)%>%
#add in title to chart
layout(title = list(
text=
paste0( input$Hospital_Type,
" hospital stay rates by drug type (",
input$Location,
"; ",
word(input$Clinical_Type,start = 1,sep = " \\("),
")"
),font = list(size = 15)),
separators = ".",
annotations =
list(x = 1.0, y = -0.25,
text = paste0("Source: Drug-Related","<br>",
"Hospital Statistics,","<br>",
"ISD Scotland (",format(Sys.Date(), "%Y"),")"),
showarrow = F, xref='paper', yref='paper',
xanchor='left', yanchor='auto', xshift=0, yshift=0,
font=list(family = "arial", size=12, color="#7f7f7f")),
yaxis = list(
exponentformat = "none",
separatethousands = TRUE,
range = c(0, max(drug_summary_new()$value, na.rm = TRUE) +
(max(drug_summary_new()$value, na.rm = TRUE)
* 10 / 100)),
title = paste0(c(
rep(" ", 20),
"EASR per 100,000 population",
rep(" ", 20),
rep("\n ", 3)
),
collapse = ""),
showline = TRUE,
ticks = "outside"
),
#Set the tick angle to minus 45. It's the only way for the x...
#axis tick labels (fin. years) to display without overlapping...
#with each other.
#Wrap the x axis title in blank spaces so that it doesn't...
#overlap with the x axis tick labels.
xaxis = list(range = c(-1,22),
tickangle = -45,
title = paste0(c(rep(" ", 20),
"<br>",
"Financial year",
rep(" ", 20),
rep("\n ", 3)),
collapse = ""),
showline = TRUE,
ticks = "outside"),
font = list(size = 13),
#Fix the margins so that the graph and axis titles have enough...
#room to display nicely.
#Set the font sizes.
margin = list(l = 90, r = 60, b = 160, t = 90),
#insert legend
showlegend = TRUE,
legend = list(bgcolor = 'rgba(255, 255, 255, 0)',
bordercolor = 'rgba(255, 255, 255, 0)')) %>%
#Remove unnecessary buttons from the modebar.
config(displayModeBar = TRUE,
modeBarButtonsToRemove = list('select2d', 'lasso2d', 'zoomIn2d',
'zoomOut2d', 'autoScale2d',
'toggleSpikelines',
'hoverCompareCartesian',
'hoverClosestCartesian'),
displaylogo = F, editable = F)
})
output$drugs_table <- renderDataTable({
datatable(drug_summary_new(),
colnames = c("Financial year",
"Hospital type",
"Clinical type",
"Drug type",
"Location",
"Rate"),
rownames = FALSE,
style = "Bootstrap",
options = list(searching= FALSE,
lengthChange= FALSE)
) %>%
formatRound(columns = 6,digits = 2)
})
#Demographic Plot
output$demographic_plot <- renderPlotly({
#first the tooltip label
tooltip_summary <- paste0(
input$summary_demographic, ": ",
demographic_summary_new()[,5],
"<br>",
"Financial year: ",
demographic_summary_new()$year,
"<br>",
"Rate: ",
formatC(demographic_summary_new()$value, big.mark = ",",
digits = 2,format = 'f')
)
#Create the main body of the chart.
plot_ly(
data = demographic_summary_new(),
#plot- we wont bother at this point with tailored colour
x = ~ year,
y = ~ value,
color = ~ demographic_summary_new()[,5],
colors =
if (input$summary_demographic == "Deprivation")
{
c("#b66dff",
"#db6d00",
"#920000",
"#006ddb",
"#490092"
)
}
else if (input$summary_demographic == "Age")
{
c("#b66dff",
"#db6d00",
"#920000",
"#006ddb",
"#490092",
"#6db6ff",
"#b6dbff"
)
}
else {
c("#920000",
"#006ddb")
}
,
#tooltip
text = tooltip_summary,
hoverinfo = "text",
#type
type = 'scatter',
mode = 'lines+markers',
marker = list(size = 8),
width = 1000,
height = 600
)%>%
#add in title to chart
layout(title = list (text= (
if (input$summary_demographic == "Deprivation")
{
paste0( input$Hospital_Type,
" hospital patient rates by deprivation quintile (",
input$Location,
"; ",
word(input$Clinical_Type,start = 1,sep = " \\("),
")")
}
else if (input$summary_demographic == "Age")
{
paste0( input$Hospital_Type,
" hospital patient rates by age group (",
input$Location,
"; ",
word(input$Clinical_Type,start = 1,sep = " \\("),
")")
}
else {
paste0( input$Hospital_Type,
" hospital patient rates by sex (",
input$Location,
"; ",
word(input$Clinical_Type,start = 1,sep = " \\("),
")")
}
),font = list(size = 15)),
separators = ".",
annotations =
list(x = 0.96, y = -0.29,
text = paste0("Source: Drug-Related","<br>",
"Hospital Statistics,","<br>",
"ISD Scotland (",format(Sys.Date(), "%Y"),")"),
showarrow = F, xref='paper', yref='paper',
xanchor='left', yanchor='auto', xshift=0, yshift=0,
font=list(family = "arial", size=12, color="#7f7f7f")),
yaxis = list(
exponentformat = "none",
separatethousands = TRUE,
range = c(0, max(demographic_summary_new()$value, na.rm = TRUE) +
(max(demographic_summary_new()$value, na.rm = TRUE)
* 10 / 100)),
title = paste0(c(
rep(" ", 20),
"EASR per 100,000 population",
rep(" ", 20),
rep("\n ", 3)
),
collapse = ""),
showline = TRUE,
ticks = "outside"
),
#Set the tick angle to minus 45. It's the only way for the x...
#axis tick labels (fin. years) to display without overlapping...
#with each other.
#Wrap the x axis title in blank spaces so that it doesn't...
#overlap with the x axis tick labels.
xaxis = list(range = c(-1,22),
tickangle = -45,
title = paste0(c(rep(" ", 20),
"<br>",
"Financial year",
rep(" ", 20),
rep("\n ", 3)),
collapse = ""),
showline = TRUE,
ticks = "outside"),
# #Fix the margins so that the graph and axis titles have enough...
# #room to display nicely.
# #Set the font sizes.
#
margin = list(l = 90, r = 60, b = 160, t = 90),