0

I would like to use metafor::rma() as a smoother for ggplot. I have tried all sorts of things to get it going, but none of it seems to work. Here's a minimum (non-)working example:

# Libraries
library(metafor)
library(ggplot2)

# Some data preparation
dat <- escalc(measure="RR", ai=tpos, bi=tneg, ci=cpos, di=cneg, data=dat.bcg)

# Scatterplot of the data
figure1 <- ggplot(dat, aes(y = yi, x = ablat)) + geom_point()
figure1

# Various attempts that lead to various error messages :(
figure2a <- ggplot(dat, aes(y = yi, x = ablat)) +
           geom_point() + geom_smooth(method = metafor::rma())

figure2b <- ggplot(dat, aes(y = yi, x = ablat)) +
  geom_point() + geom_smooth(method = metafor::rma(y = yi, vi = vi))

figure2c <- ggplot(dat, aes(y = yi, x = ablat)) +
  geom_point() + geom_smooth(method = metafor::rma(y = dat$yi, vi = dat$vi))

figure2d <- ggplot(dat, aes(y = yi, x = ablat)) +
  geom_point() + geom_smooth(method = metafor::rma(yi = yi, vi = vi, data = dat), formula = yi ~ ablat)

figure2e <- ggplot(dat, aes(y = yi, x = ablat)) +
  geom_point() + geom_smooth(method = metafor::rma(), method.args = list(yi = dat$yi, vi = dat$vi, method = "EB"))

What am I doing wrong? Thanks

  • geom_smooth may not work with metafor::rma objects? related: https://stackoverflow.com/questions/49191606/ggplot2-geom-smooth-extended-model-for-method-lm/49848195 I guess the most straight forward is to manually add your regression line +/- error intervals using for example the output of predict(your_model) – tjebo Mar 30 '20 at 10:09
  • also related.https://stackoverflow.com/questions/7005483/geom-smooth-what-are-the-methods-available I guess, although the `geom_smooth` documentation uses the word 'e.g.', it actually means 'one of... ' – tjebo Mar 30 '20 at 10:20

1 Answers1

0

I briefly tried to make it work with geom_smooth(), but I am not a heavy ggplot2 user and didn't succeed. But as @Tjebo suggested, you can compute predicted values with predict() and then use geom_line() and geom_ribbon() to add the elements. Here is an example:

library(metafor)
library(ggplot2)

dat <- escalc(measure="RR", ai=tpos, bi=tneg, ci=cpos, di=cneg, data=dat.bcg)
res <- rma(yi, vi, mods = ~ ablat, data=dat)
pred <- as.data.frame(predict(res, newmods = seq(0,60,by=1), addx=TRUE))
names(pred)[8] <- "ablat"

ggplot(dat, aes(x = ablat)) +
   geom_point(aes(y = yi)) +
   geom_line(data = pred, aes(x = ablat, y = pred)) +
   geom_ribbon(data = pred, aes(ymin = ci.lb, ymax = ci.ub), fill = "blue", alpha = 0.2)
Wolfgang
  • 2,810
  • 2
  • 15
  • 29