How to adjust the position of text automatically by using base r plot function instead of using ggplot?

I am using metafor to perform subgroup analysis. However, the position of the text in the graph producing by base r is very difficult to adjust. For example,

#The code is from the example of the author of metafor:

### copy BCG vaccine meta-analysis data into 'dat'
dat <-

### calculate log risk ratios and corresponding sampling variances (and use
### the 'slab' argument to store study labels as part of the data frame)
dat <- escalc(measure="RR", ai=tpos, bi=tneg, ci=cpos, di=cneg, data=dat,
              slab=paste(author, year, sep=", "))

### fit random-effects model
res <- rma(yi, vi, data=dat)

### a little helper function to add Q-test, I^2, and tau^2 estimate info
mlabfun <- function(text, res) {
                    " (Q = ", .(formatC(res$QE, digits=2, format="f")),
                    ", df = ", .(res$k - res$p),
                    ", p ", .(metafor:::.pval(res$QEp, digits=2, showeq=TRUE, sep=" ")), "; ",
                    I^2, " = ", .(formatC(res$I2, digits=1, format="f")), "%, ",
                    tau^2, " = ", .(formatC(res$tau2, digits=2, format="f")), ")")))}

### set up forest plot (with 2x2 table counts added; the 'rows' argument is
### used to specify in which rows the outcomes will be plotted)
forest(res, xlim=c(-16, 4.6), at=log(c(0.05, 0.25, 1, 4)), atransf=exp,
       ilab=cbind(tpos, tneg, cpos, cneg), ilab.xpos=c(-9.5,-8,-6,-4.5),
       cex=0.75, ylim=c(-1, 27), order=alloc, rows=c(3:4,9:15,20:23),
       mlab=mlabfun("RE Model for All Studies", res),
       psize=1, header=F)


The output is:
enter image description here

The position of Author is not correct. If I use mtext instead of text:

mtext(side = 3,substitute(paste(bold('Author'))),cex=0.75)

enter image description here

The Author will be the top center instead of the top left margin.

Is there any function to adjust the position more easily? Thank you!

If I use mtext('test',side = 3,adj = 0),
the graph will be like this:

enter image description here

which is not the graph I want.

My target output is something like this:
enter image description here

>Solution :

This seems to work

mtext('test',side = 3,adj = 0)

or using "at":

mtext('test',side = 3, at=par("usr")[1]+0.05*diff(par("usr")[1:2]))

Edit to address ggplot comment:

ggplot(data = data.frame(x=1,y=1)) +
geom_point(aes(x=x,y=y)) +
ggtitle('title') + 
theme(plot.title = element_text(hjust = 0))

The last line is the key, location adjusted by hjust argument
you’ll have to mess around with the numbers to align where you want

Leave a Reply