How to fix text using mtext function in R

I struggle to fix text in my plot using mtext

Assuming this is my data:

df<-rnorm(100,12,2)

The codes used are :

plot(df)
mtext(col="red",side=3,line=1,at=39, paste(round(12,4)))
mtext('text here=',col="dark green", side=3, line=1, at=10)

When I use these codes, I get a gap between 'text here=' and the value of '12'. When I fix it, and when I expand the plot area in Rstudio, I will get the gap.

I want to have text here= 12 and when I expand the plot, it is not going to be changed. It would be good if we could simplify the codes.

2 Answers

You could use a phantom expression with bquote for that:

Edit:To adjust the position, use adj and padj.

df<-rnorm(100,12,2)
plot(df)
txt1 <- bquote(expression("text here = " * phantom(.(round(12,4)))))
txt2 <- bquote(expression(phantom("text here = ") * .(round(12,4))))
mtext(eval(txt1), col = "dark green", adj=0, padj=-1)
mtext(eval(txt2), col = "red", adj=0, padj=-1)

Created on 2020-03-28 by the reprex package (v0.3.0)

0

My answer will look as a hack because it is a hack:

plot(df)
mtext(col=c("red","blue"), side=3, line=1, at=10, c('text here = ', paste0(c(rep(" ", 23), 12), collapse = "")))

You will have to find how many spaces you have to use (here is 23) before the number you want to appear (12). Resizing the plot did not change the relative positions between the text and number.

Of course, this will be difficult to adapt if the text varies from graph to graph.

I hope someone else comes with a better answer. Great answer by @user12728748 !

0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like