I wrote a function to draw forest plots of CIs from regression results.
I feed to the function a data.frame with predictor label ($label), estimates ($coef), low and
You can get the results you want by creating two ggplot
objects and putting them together via gridExtra::grid.draw
.
Set up
library(ggplot2)
library(gridExtra)
library(grid)
regression_results <-
structure(list(label = structure(c(9L, 4L, 8L, 2L, 6L, 10L, 3L, 7L, 1L, 5L),
.Label = c(" - frattura esposta", " - frattura esposta 2", " - lembo di perone vs lembo corticoperiostale", " - lembo di perone vs lembo corticoperiostale 2", " - sesso maschile vs femminile", " - sesso maschile vs femminile 2", " - trauma bassa energia", " - trauma bassa energia 2", "Tempo di guarigione 2:", "Tempo di guarigione:"),
class = "factor"),
coef = c(NA, 0.812, 0.695, 1.4, 0.682, NA, 0.812, 0.695, 1.4, 0.682),
ci.low = c(NA, 0.405, 0.31, 1.26, 0.0855, NA, 0.405, 0.31, 1.26, 0.0855),
ci.high = c(NA, 1.82, 0.912, 2.94, 1.01, NA, 1.82, 0.912, 2.94, 1.01),
style = structure(c(1L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L),
.Label = c("bold", "plain"), class = "factor")),
.Names = c("label", "coef", "ci.low", "ci.high", "style"),
class = "data.frame",
row.names = c(NA, -10L))
# Set a y-axis value for each label
regression_results$yval <- seq(nrow(regression_results), 1, by = -1)
Build a forest plot
# Forest plot
forest_plot <-
ggplot(regression_results) +
theme_bw() +
aes(x = coef, xmin = ci.low, xmax = ci.high, y = yval) +
geom_point() +
geom_errorbarh(height = 0.2, color = 'red') +
geom_vline(xintercept = 1) +
theme(
axis.text.y = element_blank(),
axis.title.y = element_blank(),
axis.ticks.y = element_blank(),
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
panel.border = element_blank()
) +
ylim(0, 10) +
xlab("Odds Ratio")
build a plot of labels
# labels, could be extended to show more information
table_plot <-
ggplot(regression_results) +
theme_bw() +
aes(y = yval) +
geom_text(aes(label = gsub("\\s2", "", label), x = 0), hjust = 0) +
theme(
axis.text = element_blank(),
axis.title = element_blank(),
axis.ticks = element_blank(),
panel.grid = element_blank(),
panel.border = element_blank()
) +
xlim(0, 6) +
ylim(0, 10)
Produce the Plot
# build the plot
png(filename = "so-example.png", width = 8, height = 6, units = "in", res = 300)
grid.draw(gridExtra:::cbind_gtable(ggplotGrob(table_plot), ggplotGrob(forest_plot), size = "last"))
dev.off()