-
Notifications
You must be signed in to change notification settings - Fork 0
/
local_profile.Rmd
executable file
·266 lines (201 loc) · 8.96 KB
/
local_profile.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
---
title: ""
output: pdf_document
geometry: margin=0.5cm
params:
reactive_df: NA
chosen_area: NA
chosen_sex: NA
chosen_geography_level: NA
header-includes:
- \usepackage[default]{sourcesanspro}
- \usepackage[T1]{fontenc}
- \usepackage{fancyhdr}
- \usepackage{graphicx}
- \usepackage{longtable}
- \usepackage{tabu}
- \usepackage{booktabs}
- \usepackage{array}
- \usepackage{multirow}
- \usepackage{wrapfig}
- \usepackage{float}
- \usepackage{colortbl}
- \usepackage{pdflscape}
- \usepackage{threeparttable}
- \usepackage{threeparttablex}
- \usepackage[normalem]{ulem}
- \usepackage{makecell}
- \usepackage{xcolor}
- \usepackage{hyperref}
- \newcommand{\blandscape}{\begin{landscape}}
- \newcommand{\elandscape}{\end{landscape}}
mainfont: SourceSansPro
---
```{r, include=FALSE}
options(tinytex.verbose = TRUE)
```
```{r echo=FALSE, message= FALSE}
library(ggplot2)
library(dplyr)
library(kableExtra)
library(tidyr)
library(knitr)
library(stringr)
chosen_area <- gsub("&", "\\\\&", params$chosen_area)
mydate <- Sys.Date()
```
\blandscape
\begin{minipage}{0.7\textwidth}
\raggedright
\textbf{\large{PHS Adult Mental Health Indicators}} \\
\large{Local area profile for `r chosen_area` (`r params$chosen_geography_level`)}\\
Sex: `r params$chosen_sex` \\
Downloaded on: `r mydate` \\
From: Public Health Scotland's Adult Mental Health Indicators dashboard \\
\end{minipage}
\hfill
\begin{minipage}{0.3\textwidth}
\raggedleft
\includegraphics[width=100pt]{phs-logo-updated.png}
\end{minipage}
\bigskip
\begin{minipage}{0.8\textwidth}
\raggedright
\bigskip
\large{This local profile compares the latest available indicator data for the selected area (`r chosen_area`) with data for the other `r params$chosen_geography_level`s and the Scottish average.} \par
\bigskip
\large{The grey 'spine chart' bar shows the range of values for each indicator, and the circle shows where the selected area places within the range, as shown in this image. The red line indicates the Scottish average. The colour of the circle indicates whether the value in the selected area is significantly 'worse' than the Scottish average (yellow), significantly 'better' (blue), or not significantly different (grey). Data for individual indicators can be viewed and downloaded on the dashboard.} \par
\bigskip
\large{The profile is intended to increase understanding of local health issues and to prompt further investigation, rather than to be used as a performance assessment or benchmarking tool. Local knowledge is needed to understand and interpret differences, as there can be many reasons why an indicator is higher in one area compared to another.}
\end{minipage}
\begin{minipage}{0.3\textwidth}
\raggedleft
\includegraphics[width=250pt]{spine.png}
\includegraphics[width=250pt]{local_profile_legend.png}
\end{minipage}
```{r setup, include=FALSE, dev="cairo_pdf"}
knitr::opts_chunk$set(warning = FALSE, message = FALSE)
knitr::opts_chunk$set(fig.pos = "H", out.extra = "")
```
```{r echo=FALSE, message= FALSE}
# function to create spine plot for each indicator
create_spine_plot <- function(data, chosen_area_colour) {
plot <- ggplot(data, aes(x = ind_name, y = GraphPoint, fill = fct_rev(intervals))) + # intervals need reversing to plot correctly
geom_bar(stat = "identity", width = 0.75) +
scale_fill_manual(values = c("int1" = 'white', "int2" = '#D3D3D3', "int3" = '#A4A4A4', "int4" = '#D3D3D3', "int5" = 'white')) +
geom_hline(yintercept = 0.5, col = "red") +
ylim(0, 1) +
geom_point(data = NULL, aes(x = ind_name, y = new_chosen_value), shape = 19, size = 4, col = chosen_area_colour) +
coord_flip() +
theme_void() +
guides(fill = "none") +
theme(plot.margin = unit(c(0, 0, 0, 0), "cm"),
plot.background = element_rect(fill = "white", color = "white"),
panel.background = element_rect(fill = "white", color = "white")
)
return(plot)
}
# function to create sparkline for each indicator
create_sparkline <- function(data) {
plot <- ggplot(data, aes(x=1:length(trend), y=as.numeric(trend))) +
geom_line(linewidth=2, colour='#0078D4') +
geom_area(fill="#E6F2FB") +
theme_void() +
guides(fill = "none") +
scale_y_continuous(limits=c(0, NA), expand = expansion(mult = c(0, 0.2))) +
theme(plot.margin = unit(c(0, 0, 0, 0), "cm"),
plot.background = element_rect(fill = "white", color = "white"),
panel.background = element_rect(fill = "white", color = "white"))
return(plot)
}
# temporary folder to save charts to
graph_directory <- tempdir()
# # pivot reactive dataframe in longer format (required for ggplot)
df <- params$reactive_df %>%
select(domain, ind_name, short_definition, year_range, int1, int2, int3, int4, int5, scotland = scotland_value, value, new_chosen_value, marker_colour, trend) %>%
pivot_longer(cols = c(int1, int2, int3, int4, int5), values_to = "GraphPoint", names_to = "intervals") %>%
# order quantiles so stack in correct order
mutate(intervals = factor(intervals, levels = c("int1", "int2", "int3", "int4", "int5")))
# the data to be displayed in table
table <- df %>%
select(domain, ind_name, short_definition, value, scotland, year_range, trend) %>%
distinct() %>%
mutate(ind = paste0(
"\\textbf{",ind_name, "}\n", "\\textit{", short_definition, " ", year_range, ".}")) %>%
mutate(id = row_number(),
spine ="") %>% #placeholder, so there are enough cols
select(domain, ind, id, value, scotland, spine)
table$ind <- linebreak(table$ind)
# get unique indicator list
unique_indicators <- unique(df$ind_name)
# Counter variable to keep track of which chart being generated
counter <- 1
# Iterate over each indicator and create/save a spineplot
for (ind_name in unique_indicators) {
# Filter the data for the current indicator
indicator_data <- df %>% filter(ind_name == !!ind_name)
# get colour for point
chosen_area_colour <- unique(indicator_data$marker_colour)
# create the plot
plot <- create_spine_plot(indicator_data, chosen_area_colour)
# create filename
filename <- sprintf("%s/%s.png", graph_directory, counter)
# Save the plot as a PNG with the filename created
ggsave(filename, plot = plot, units="mm", width=50, height=5, dpi=300)
# Unnest the trend column for plotting
indicator_data <- indicator_data[1,] %>% # 1st row, as contents of trend column will be repeated for the same indicator
select(trend) %>%
unnest(cols = c(trend))
# create the plot
plot2 <- create_sparkline(indicator_data)
# create filename
filename2 <- sprintf("%s/spark%s.png", graph_directory, counter)
# Save the plot as a PNG with the filename created
ggsave(filename2, plot = plot2, units="mm", width=15, height=5, dpi=300)
# increase counter variable
counter <- counter + 1
}
# define column headers for the pdf table
col_names = c("Domain", "Indicator", "Time trend",
chosen_area, "Scotland",
"Spine chart"
)
```
```{r, echo= FALSE, message = FALSE}
# the final table to be displayed with charts embedded
table %>%
group_by(domain) %>%
knitr::kable(
format = "latex", # must be in latex format for pdf download
booktabs = TRUE, # generic formatting
escape = FALSE, # ensures latex formatting on indicator column works (i.e.bold/italics,linebreaks)
longtable = TRUE, # ensures table goes across multiple pages when too long
align = c("llllll"), #left alignment within cells
col.names = col_names
) %>%
# format header
row_spec(0, background = "#032F4F", color = "white") %>%
add_header_above(., c(" " = 3,
"Latest values" = 3),
escape = TRUE,
background = "#032F4F", color = "white") %>%
# set column widths
column_spec(1, width = "8em") %>% # domain column
column_spec(2, width = "20em") %>% # indicator column
# embed chart images on each row of column 6
kableExtra::column_spec(3, width = "6em",
image = sprintf("%s/spark%s.png", graph_directory, table$id), color = "white") %>%
column_spec(4, width = "6em") %>% # chosen area column
column_spec(5, width = "3em") %>% # scotland column
# embed chart images on each row of column 5
kableExtra::column_spec(6, width = "20em",
image = sprintf("%s/%s.png", graph_directory, table$id), color = "white") %>%
# repeats column headings when table goes across multiple pages
kable_styling(latex_options = c("repeat_header")) %>%
# add footnote with link to profiles tool
footnote(general="\\\\url{https://scotland.shinyapps.io/phs-adult-mhi-dashboard/}",
general_title = "Source: ", footnote_as_chunk = T, escape=F) %>%
# prevent domain from appearing on every row of column
kableExtra::collapse_rows(columns = 1, valign = "top", row_group_label_position = "first", custom_latex_hline = 2:6, longtable_clean_cut = F)
```
\elandscape