-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfrequentist_bayesian_plot.R
More file actions
192 lines (149 loc) · 8.46 KB
/
frequentist_bayesian_plot.R
File metadata and controls
192 lines (149 loc) · 8.46 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
# Presenting frequentist and Bayesian estimates in the same plot. For this
# purpose, the frequentist results are merged into a plot from
# brms::mcmc_plot(), Three arguments are required for this function: a
# summary of an 'lmerTest' model, confidence intervals from
# lme4::confint.merMod(), and a plot from brms::mcmc_plot(). The function
# is equipped to accept the slight differences between the names of the
# predictors in the frequentist results and in the Bayesian results.
frequentist_bayesian_plot =
function( frequentist_model_summary, confidence_intervals, mcmc_plot,
labels = NULL, font_size = 10, x_title = 'Estimate',
x_axis_labels = 6, # <-- approximate number of labels in X axis
# Number of columns into which the legend labels (i.e.,
# 'Frequentist analysis', 'Bayesian analysis') should
# be distributed.
legend_ncol = 2,
# If note_frequentist_no_prior = TRUE, '(no prior)' is appended to the
# label 'Frequentist analysis' in the legend. This is useful when
# the plot is titled with the prior, to clarify that the prior
# does not concern the frequentist analysis.
note_frequentist_no_prior = FALSE,
# If interaction_symbol_x = TRUE, replace double colons with times
# symbols followed by line breaks and indentation. Then, replace
# single colons with times symbols.
interaction_symbol_x = FALSE,
# Vertical line at specified value of X axis
vertical_line_at_x = NULL ) {
require(dplyr)
require(forcats)
require(ggplot2)
require(stringr)
require(ggtext)
# Format frequentist results to match the format of mcmc_plot
# Firstly, remove parentheses from the intercept and add 'b_'
# to the beginning of every predictor
rownames(frequentist_model_summary$coefficients) =
rownames(frequentist_model_summary$coefficients) %>%
str_replace(pattern = '\\(Intercept\\)', replacement = 'Intercept') %>%
str_replace(pattern = '^', replacement = 'b_')
rownames(confidence_intervals) =
rownames(confidence_intervals) %>%
str_replace(pattern = '\\(Intercept\\)', replacement = 'Intercept') %>%
str_replace(pattern = '^', replacement = 'b_')
# Next, create 'parameters' column in the frequentist results
frequentist_model_summary$coefficients =
frequentist_model_summary$coefficients %>% as.data.frame() %>%
mutate(parameter = rownames(frequentist_model_summary$coefficients)) %>%
rename(frequentist_estimate = Estimate) %>%
data.frame(row.names = NULL)
confidence_intervals =
confidence_intervals %>% as.data.frame() %>%
mutate(parameter = rownames(confidence_intervals)) %>%
rename(CI_2.5 = '2.5 %', CI_97.5 = '97.5 %') %>%
data.frame(row.names = NULL)
# Merge both frequentist objects into mcmc_plot
mcmc_plot$data =
list(mcmc_plot$data,
frequentist_model_summary$coefficients %>%
select(parameter, frequentist_estimate),
confidence_intervals) %>%
purrr::reduce(full_join, by = 'parameter')
# If labels supplied and interaction_symbol_x = TRUE, replace double
# colons with times symbols followed by line breaks and indentation.
# Then, replace single colons with times symbols.
if(!is.null(labels) & isTRUE(interaction_symbol_x)) {
labels = labels %>%
gsub('::', ' × <br> ', .) %>%
gsub(':', ' × ', .)
}
# Set current order of effects to prevent alphabetical order
labels = factor(labels, levels = labels)
# Plot
plot = mcmc_plot +
# Add vertical line (on top of default line from mcmc_plot)
geom_vline(xintercept = vertical_line_at_x, col = 'grey60') +
# Add confidence intervals from frequentist model
geom_errorbarh(aes(xmin = CI_2.5, xmax = CI_97.5),
height = 0.12, position = position_nudge(y = 0.09),
colour = '#ff7474ff') +
# Add frequentist estimate
geom_point(aes(x = frequentist_estimate),
position = position_nudge(y = 0.09),
colour = 'red', size = 0.8) +
scale_x_continuous(n.breaks = x_axis_labels,
limits = c(min(mcmc_plot$data$CI_2.5, mcmc_plot$data$x),
max(mcmc_plot$data$CI_97.5, mcmc_plot$data$x))) +
scale_y_discrete(expand = c(0.023, 0.033)) +
# X-axis title
xlab(x_title) +
theme_minimal() +
theme(text = element_text(family = 'Arial'), # <-- prevent R crashing (see https://discourse.mc-stan.org/t/error-code-when-using-pp-check-with-brms/27419/4)
plot.title = element_markdown(colour = '#005b96', hjust = 0.5, vjust = 1,
size = font_size * 1.2),
axis.title.x = ggtext::element_markdown(size = font_size,
margin = margin(t = font_size * 0.8)),
axis.text.x = element_text(size = font_size * 0.9,
margin = margin(t = font_size * 0.4)),
axis.title.y = element_blank(),
# Use 'vjust' used to place each Y axis label at the foot of its respective segment
axis.text.y = ggtext::element_markdown(size = font_size, vjust = 0),
axis.ticks.x = element_line(),
# Parameters are adjusted based on number of columns in legend using ifelse()
legend.text = element_text(size = font_size,
lineheight = ifelse(legend_ncol == 1, 0.3, 1.2),
margin = margin(r = ifelse(legend_ncol == 1, 2, 4))),
legend.key.height = unit(ifelse(legend_ncol == 1, 15, 21), 'pt'),
legend.background = element_rect(colour = 'grey70', fill = 'white'),
panel.grid.major.y = element_line(colour = 'grey90'),
plot.margin = margin(9, 4, 14, 12))
# If labels supplied, pass them to 'scale_y_discrete'. This is necessary
# because modifying the 'parameter' column directly creates errors in
# the plot.
if(!is.null(labels)) {
plot = plot +
# Apply modified labels, in a reverse order to match correct order pre-established
# by the 'mcmc_plot' function that was used to create the original plots
# (see https://discourse.mc-stan.org/t/manually-changing-y-axis-tick-labels-in-brms-mcmc-plot/19727/5)
scale_y_discrete(labels = rev(labels), limits = rev,
# Padding at the borders
expand = c(0.023, 0.033))
}
# Manual legend for frequentist analysis (red) and Bayesian analysis (blue),
# subject to the presence of 'note_frequentist_no_prior'.
if(note_frequentist_no_prior) {
plot$data = plot$data %>%
mutate(method = rep(c('Frequentist analysis\n(no prior)',
'Bayesian analysis'),
times = n()/2))
plot = plot +
geom_line(aes(colour = factor(method)), alpha = 0) + # <-- placeholder to allow manual scale
scale_colour_manual(values = c('Frequentist analysis\n(no prior)' = 'red',
'Bayesian analysis' = '#005b96'), # <-- blue
guide = guide_legend(title = NULL,
override.aes = list(alpha = 1, linewidth = 5),
ncol = legend_ncol))
} else {
plot$data = plot$data %>%
mutate(method = rep(c('Frequentist analysis', 'Bayesian analysis'),
times = n()/2))
plot = plot +
geom_line(aes(colour = factor(method)), alpha = 0) + # <-- placeholder to allow manual scale
scale_colour_manual(values = c('Frequentist analysis' = 'red',
'Bayesian analysis' = '#005b96'), # <-- blue
guide = guide_legend(title = NULL,
override.aes = list(alpha = 1, linewidth = 4),
ncol = legend_ncol))
}
# Output
plot
}