user1946911
user1946911

Reputation: 97

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.

Upvotes: 0

Views: 999

Answers (2)

user12728748
user12728748

Reputation: 8516

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)

Upvotes: 2

R. Schifini
R. Schifini

Reputation: 9313

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 !

Upvotes: 0

Related Questions