-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzz_utils_aggregation.R
More file actions
355 lines (297 loc) · 13.1 KB
/
zz_utils_aggregation.R
File metadata and controls
355 lines (297 loc) · 13.1 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
# Aggregation Plot - SWIMS
swims.plot.aggregation <- function(var,
institution_prov = NULL,
data = dat,
codeb = codebook,
fill_colors = NULL,
colors_set = "RdYlBu",
showCount = F,
font_size = 12,
width_bar = 0.5,
annoFontSize = 8,
proportion.label = F,
show.percentages = T,
count_votes_at_all = FALSE # Creates plot only showing how many did something at all
){
# Example
#var <- "qrp_pressure"
#institution_prov <- target_institution
# data <- dat
# codeb <- codebook
# fill_colors <- NULL
# colors_set <- "Accent"
# showCount <- F
# font_size <- 12
# width_bar <- 0.5
# annoFontSize <- 8
# count_votes_at_all <- F
# PREPARATION ####
# Define variable
var_org <- var
var <- codeb[codeb$Category %in% var,"VarName"]
var_text <- data.frame("variable" = var,"text" = codeb[codeb$VarName %in% var,"Label"])
# Modify institution_prov
if(!is.null(institution_prov)){
institution_prov <- remove_before_and_comma(institution_prov)
dat$institution <- remove_before_and_comma(dat$institution)
}
# Ensure var exists in the codeb
if (!all(var %in% codeb$VarName)) {
stop(paste("Variable", var, "not found in the codeb."))
}
# Use variable label if available
x_label <- strsplit(codeb[codeb$VarName %in% var,"Labels"],"//")[[1]]
# SUB-PART: COUNT VOTES AT ALL ####
if(count_votes_at_all){
side_obj <- data %>%
mutate(n_quoted = rowSums(across(all_of(var), ~ . == "quoted", .names = "check_{.col}"), na.rm = TRUE))
if(is.null(institution_prov)){
# How many quoted something
quot_dat <- side_obj %>%
filter(n_quoted > 0) %>%
nrow()
# How many did not quote something
non_quot_dat <- side_obj %>%
filter(n_quoted == 0) %>%
nrow()
# Mean quoted
mean_quot_dat <- side_obj %>%
filter(n_quoted > 0)
mean_quot_dat <- mean(mean_quot_dat$n_quoted)
# plot
plot_data <- data.frame(
group = c("At least one dimension reported", "No dimension reported"),
count = c(quot_dat, non_quot_dat),
Percentage = c(quot_dat / sum(quot_dat, non_quot_dat), non_quot_dat / sum(quot_dat, non_quot_dat))
)
plot_function <- function(plot_data) {
g <- ggplot(plot_data, aes(x = "Witnessed/Experienced by ...\n\n", y = Percentage, fill = group)) +
geom_bar(stat = "identity", width = width_bar) +
labs(
x = paste("Mean number of dimensions reported by an individual:", round(mean_quot_dat, 2)),
y = "Percentage",
fill = "Category"
#title = "In cases where you have experienced or witnessed bullying, discrimination, harassment, or other unfair treatment, were such behaviors related to…"
) +
# coord_flip(clip = "off") +
scale_y_continuous(labels = scales::percent) +
theme_minimal() +
theme(
text = element_text(size = font_size),
axis.ticks.x = element_blank(),
axis.text.y = element_text(size = font_size),
axis.title = element_text(size = font_size),
legend.position = "right",
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
plot.title = element_text(size = font_size, hjust = 0.5)
)
if(showCount){
g <- g + geom_text(aes(label = paste0("N = ", count)), vjust = -0.5, size = annoFontSize, color = "black")
}
if(show.percentages){
g <- g + geom_text(aes(label = paste0(round(Percentage * 100, 0), "%")), position = position_stack(vjust = 0.5), size = annoFontSize, color = "white")
}
return(g)
}
g <- plot_function(plot_data)
return(g)
} else if(!is.null(institution_prov)){
side_obj <- side_obj %>%
filter(institution == institution_prov)
# How many quoted something
quot_dat <- side_obj %>%
filter(n_quoted > 0) %>%
nrow()
# How many did not quote something
non_quot_dat <- side_obj %>%
filter(n_quoted == 0) %>%
nrow()
# Mean quoted
mean_quot_dat <- side_obj %>%
filter(n_quoted > 0)
mean_quot_dat <- mean(mean_quot_dat$n_quoted)
# plot
plot_data <- data.frame(
group = c("At least one dimension reported", "No dimension reported"),
count = c(quot_dat, non_quot_dat),
Percentage = c(quot_dat / sum(quot_dat, non_quot_dat), non_quot_dat / sum(quot_dat, non_quot_dat))
)
plot_function <- function(plot_data) {
g <- ggplot(plot_data, aes(x = "Witnessed/Experienced by ...\n\n", y = Percentage, fill = group)) +
geom_bar(stat = "identity", width = width_bar) +
labs(
x = paste("Mean number of dimensions reported by an individual:", round(mean_quot_dat, 2)),
y = "Percentage",
fill = "Category"
#title = "In cases where you have experienced or witnessed bullying, discrimination, harassment, or other unfair treatment, were such behaviors related to…"
) +
# coord_flip(clip = "off") +
scale_y_continuous(labels = scales::percent) +
theme_minimal() +
theme(
text = element_text(size = font_size),
axis.ticks.x = element_blank(),
axis.text.y = element_text(size = font_size),
axis.title = element_text(size = font_size),
legend.position = "right",
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
plot.title = element_text(size = font_size, hjust = 0.5)
)
if(showCount){
g <- g + geom_text(aes(label = paste0("N = ", count)), vjust = -0.5, size = annoFontSize, color = "black")
}
if(show.percentages){
g <- g + geom_text(aes(label = paste0(round(Percentage * 100, 0), "%")), position = position_stack(vjust = 0.5), size = annoFontSize, color = "white")
}
return(g)
}
g <- plot_function(plot_data)
return(g)
}
}
# PREPROCESSING ####
if(!is.null(institution_prov)){ # with institution
# Prepare data for plotting
obj <- lapply(var, function(x){
data %>%
mutate(group = ifelse(institution == institution_prov, paste0(institution_prov), "Other Institutions")) %>%
mutate(group = factor(group, levels = c("Other Institutions", setdiff(levels(factor(group)), "Other Institutions")))) %>%
filter(if_all(all_of(x), ~ !is.na(.)), !is.na(group)) %>%
pivot_longer(cols = all_of(x), names_to = "variable", values_to = "value") %>%
group_by(group, variable, value) %>%
summarise(count = n(), .groups = "drop") %>%
group_by(group, variable) %>%
mutate(proportion = count / sum(count),
n_total = sum(count)) %>%
ungroup()
})
plot_data <- bind_rows(obj)
plot_data <- plot_data %>%
left_join(var_text, by = "variable") %>%
select(-variable) %>%
mutate(text = factor(text, levels = var_text$text)) %>%# Order responses correctly
mutate(text = str_wrap(text, width = 20)) %>%
filter(value %in% "quoted") %>%
group_by(group) %>%
mutate(Percentage = count / sum(count))
# Rearrange group
plot_data <- plot_data %>%
arrange(group == "Other Institutions")
plot_data$group <- sapply(plot_data$group, remove_before_and_comma)
plot_data$group <- factor(plot_data$group, levels = c(institution_prov, "Other Institutions"))
} else if(is.null(institution_prov)){ # without institution)
obj <- lapply(var, function(x){
data %>%
filter(if_all(all_of(x), ~ !is.na(.))) %>% # Remove NAs in selected variables
pivot_longer(cols = all_of(x), names_to = "variable", values_to = "value") %>%
group_by(variable, value) %>%
summarise(count = n(), .groups = "drop") %>%
group_by(variable) %>%
mutate(proportion = count / sum(count),
n_total = sum(count)) %>%
ungroup()
})
plot_data <- bind_rows(obj)
# Merge labels for variables
plot_data <- plot_data %>%
left_join(var_text, by = "variable") %>%
select(-variable) %>%
mutate(text = str_wrap(text, width = 20)) %>%
mutate(text = factor(text, levels = str_wrap(var_text$text, width = 20))) %>%
filter(value %in% "quoted") %>%
mutate(Percentage = count / sum(count))
}
# Define fill colors if not provided
if(is.null(fill_colors)){
fill_colors <- RColorBrewer::brewer.pal(n = min(length(unique(plot_data$text)), 9), name = colors_set)
if (length(unique(plot_data$text)) > 9) {
fill_colors <- colorRampPalette(fill_colors)(length(unique(plot_data$text)))
}
}
# PLOTTING ####
if(!is.null(institution_prov)){
plot_function <- function(plot_data) {
# Order levels
plot_data$text <- as.factor(plot_data$text)
plot_data$text <- fct_relevel(plot_data$text, "Unknown", "Prefer not to say", "No, no one", after = Inf)
# Plot erstellen
g <- ggplot(plot_data[plot_data$value %in% "quoted",], aes(x = group, y = count, fill = text)) +
geom_bar(stat = "identity", position = "fill", width = width_bar, color = "white", linewidth = 0.15) + # Stacked Bar Chart
labs(
x = NULL, # Entferne x-Achsen-Beschriftung
y = "Percentage of Among All Named Categories",
fill = "Category",
title = ""
# title = paste0("Comparison of Responses by Institution: ", var_org
#)
) +
scale_fill_manual(values = fill_colors) +
scale_y_continuous(labels = scales::percent) +
theme_minimal() +
theme(
text = element_text(size = font_size),
axis.text.x = element_text(size = font_size, angle = 45, hjust = 1),
axis.text.y = element_text(size = font_size),
axis.title = element_text(size = font_size),
legend.text = element_text(size = font_size),
legend.title = element_text(size = font_size),
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
plot.title = element_text(size = font_size, hjust = 0.5)
) +
scale_x_discrete(labels = function(x) str_wrap(x, width = 30)) # Apply text wrapping
if(showCount){
g <- g + geom_text(aes(label = count), position = position_fill(vjust = 0.5), size = annoFontSize, color = "white")
}
if(show.percentages){
# Note: Added vjust shift so it doesn't overlap perfectly with showCount if both are TRUE
g <- g + geom_text(aes(label = paste0(round(Percentage * 100, 0), "%")), position = position_fill(vjust = 0.7), size = annoFontSize, color = "white")
}
return(g)
}
} else if(is.null(institution_prov)){
plot_function <- function(plot_data) {
g <- ggplot(plot_data, aes(x = "", y = Percentage, fill = text)) +
geom_bar(stat = "identity", width = width_bar, color = "white", linewidth = 0.15) +
labs(
x = NULL,
y = "Percentage",
fill = "Category",
title = ""
) +
scale_fill_manual(values = fill_colors) +
scale_y_continuous(labels = scales::percent) +
theme_minimal() +
theme(
text = element_text(size = font_size),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.text.y = element_text(size = font_size),
axis.title = element_text(size = font_size),
legend.position = "right",
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
plot.title = element_text(size = font_size, hjust = 0.5)
)
if(showCount){g <- g + geom_text(aes(label = count), vjust = -0.5, size = annoFontSize, color = "black") }
if (proportion.label) {
g <- g + geom_text(aes(label = paste0(round(Percentage * 100, 1), "%")),
position = position_stack(vjust = 0.5), color = "white")
}
if (show.percentages) {
g <- g + geom_text(aes(label = paste0(round(Percentage * 100, 0), "%")),
position = position_stack(vjust = 0.5), size = annoFontSize, color = "white")
}
return(g)
# if(showCount){
# return(g + geom_text(aes(label = count), vjust = -0.5, size = annoFontSize, color = "black"))
# } else {
# return(g)
# }
}
}
# RETURN ####
plot_function(plot_data)
}