I want to create a forest plot of results from a heirarchical model so that the variable name appears on the y-axis and the names of each level in the heirarchy appear below (ideally indented from the variable name).
I have the following example:
library(tidyverse); theme_set(theme_classic())
# Create example data
data <- data.frame(variable = c(rep("Covariate1",3), rep("Covariate 2",3),
rep("Covariate3",3)),
posterior = rep(c("GroupA", "GroupB", "GroupC"),3),
mu = c(0.25, 0.08, 0.07, 0.27, -0.45, 0.01,
0.37, 0.002, 0.24),
colour = rep(c("red","blue","yellow")))
data$est <- paste(data$variable, data$posterior, sep="_")
data
# variable posterior mu colour est
#1 Covariate1 GroupA 0.250 red Covariate1_GroupA
#2 Covariate1 GroupB 0.080 blue Covariate1_GroupB
#3 Covariate1 GroupC 0.070 yellow Covariate1_GroupC
#4 Covariate 2 GroupA 0.270 red Covariate 2_GroupA
#5 Covariate 2 GroupB -0.450 blue Covariate 2_GroupB
#6 Covariate 2 GroupC 0.010 yellow Covariate 2_GroupC
#7 Covariate3 GroupA 0.370 red Covariate3_GroupA
#8 Covariate3 GroupB 0.002 blue Covariate3_GroupB
#9 Covariate3 GroupC 0.240 yellow Covariate3_GroupC
plot1 <- data |>
ggplot(aes(y = fct_rev(reorder(est, as.numeric(row.names(data)))))) +
geom_point(aes(x=mu), shape=16, size=3.5, colour=data$colour) +
geom_vline(xintercept = 0, linetype="solid",
linewidth=0.3, colour="gray70") +
labs(x="Effect size", y="") +
coord_cartesian(xlim=c(-0.5, 0.5), ylim=c(1,9)) +
ggtitle("My Title")
plot1
I created the vector est
to help explain the problem. I would like the y-axis labels to be more like this, using variable
and posterior
:
Covariate1
GroupA
GroupB
GroupC
Covariate2
GroupA
GroupB
GroupC
Covariate3
GroupA
GroupB
GroupC
with a space between the covariates. Does anyone know how to do that? So far I've only found solutions for evenly increasing/decreasing space between all y-axis items, but I need something more customised to group my data.
I didn't use ggforestplot
as I have a different statistical model for each covariate in the plot (plus confidence intervals, not included here) and I couldn't get it to work.