开发者

How to add nice formated anotations to a R base graph using expression and the value of a variable?

开发者 https://www.devze.com 2023-01-17 21:15 出处:网络
Say, I have a variable rv which has some numerical value. Now, I want to plot the value of this variable on a base plot but preceded by a nicely formatted symbol e.g., r subscript m, using expression.

Say, I have a variable rv which has some numerical value. Now, I want to plot the value of this variable on a base plot but preceded by a nicely formatted symbol e.g., r subscript m, using expression. To write on the plot I use mtext.

However, what I get is either the value of the variable, but no nicely formatted symbol (left annotation), or a nicely formatted symbol, but not the val开发者_JAVA百科ue of the variable, but the variable name...

I tried to play around with eval, but didn't get what I wanted. Here is my code:

plot(1:10, rep(10,10), ylim=c(0,12))
rv <- 0.43

#left annotation:
mtext(paste(expression(italic(r[M])), " = ", rv), side = 1, line = -1.5, adj = 0.1)
#right annotation:
mtext(expression(paste(italic(r[M]), " = ", rv)), side = 1, line = -1.5, adj = 0.9)

This is the result:

How to add nice formated anotations to a R base graph using expression and the value of a variable?

How do i get both, nice format and value of the variable? Thanks.

btw: I know that I can get it, if I use two times mtext and play around with adj and stuff. But I would really like to get it in one call or without playing around with the position of two annotations.


The bquote function will create an expression and alow substitution of values using .(var) syntax. for your case do something like:

text( 5,1, bquote( italic(r[M]) == .(rv) ) )


Just combine what you have and plot two pieces, joined by using adj:

R> plot(1:10, rep(10,10), ylim=c(0,12))
R> text(2,12, expression(paste(italic(r[M]))), adj=1)
R> text(2,12, paste("=", rv), adj=0)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号