How do I include a superscript to texts on a plot on R?

徘徊边缘 提交于 2020-01-02 01:05:10

问题


I need it to look like this:

R^2 = some values

And I've tried the code below but it wouldn't work, it came out as "R (expression (^2)) = some values" instead:

text (25, 200, paste ("R (expression (^2)) =", round (rsquarelm2, 2)))

回答1:


You don't want a character vector, but an expression, hence this

expression(R^2 == 0.85)

is what you need. In this case, you want to substitute in the result of another R operation. For that you want substitute() or bquote(). I find the latter easier to work with:

rsquarelm2 <- 0.855463
plot(1:10, 1:10, type = "n")
text(5, 5, bquote(R^2 == .(round(rsquarelm2, 2))))

With bquote(), anything in .( ) is evaluated and the result is included in the expression returned.




回答2:


The paste function returns a string, not an expression. I prefer to use bquote for cases like this:

text(25, 200, bquote( R^2 == .(rs), list(rs=round(rsquarelm2,2))))



回答3:


How to include formatting and mathematical values in plots is FAQ 7.13.

For example, if ahat is an estimator of your parameter a of interest, use

title(substitute(hat(a) == ahat, list(ahat = ahat)))

(note that it is ‘==’ and not ‘=’). Sometimes bquote() gives a more compact form, e.g., title(bquote(hat(a) = .(ahat)))

where subexpressions enclosed in ‘.()’ are replaced by their values.

demo(plotmath) is also useful.


In this case, you can use either

title(substitute(R^2 = rsq, list(rsq = format(rsquarelm2, digits = 2))))

or

title(bquote(R^2 == .(format(rsquarelm2, digits = 2))))

(format is more appropriate here than round, since you want to control how the value is displayed rather than creating an approximation of the value itself.)



来源:https://stackoverflow.com/questions/18965319/how-do-i-include-a-superscript-to-texts-on-a-plot-on-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!