在绘图文本中使用表达式 - 打印变量的值而不是其名称 [英] Using an expression in plot text - Printing the value of a variable rather than its name

查看:28
本文介绍了在绘图文本中使用表达式 - 打印变量的值而不是其名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取一个包含指数的标签.这是我的代码

I am trying to get a label to have an exponent in it. Here's the code I have

vall = format(cor(x,y)*cor(x,y),digits=3)
eq <- expression(paste(R^2," = ",vall,sep=""))
text(legend.x,legend.y,eq,cex=1,font=2)

但是文字看起来就是这样

But the text simply looks like this

如何让实际的 val 显示出来(而不是文本vall")

How do I get the actual vall to show up (and not the text "vall")

推荐答案

试试bquote(),例如:

set.seed(1)
vall <- format(rnorm(1),digits=3)
eq <- bquote(bold(R^2 == .(vall)))
sq <- seq(0, 1, by = 0.1)
plot(sq, sq, type = "n")
text(0.5, 0.5, eq)

您的示例不起作用的原因是 R 永远不会评估 vall:

The reason your example doesn't work is that R never ends up evaluating vall:

> eq2 <- expression(paste(R^2," = ",vall,sep=""))
> eq2
expression(paste(R^2, " = ", vall, sep = ""))

plotmath 试图从中做出一些事情,但本质上 vall 是按字面意思理解的.

plotmath tries to make something out of this but essentially vall is taken literally.

通常在 plotmath 表达式中不需要 paste(),您可以使用标准运算符和布局运算符来构建表达式.例如,对于与示例生成的表达式等效的表达式(未求值的 vall),您真正需要的是:

In general you don't need paste() in a plotmath expression, you can build the expression up using standard operators and through the use of layout operators. For example, for an expression equivalent to the one your example produced (unevaluated vall), all you really need is:

expression(R^2 == vall)

bquote() 是一种用表达式中的值替换对象的方法.您将要替换的对象包含在 .( ) 中.然后,R 将查找该对象并获取其值并将其插入表达式中.

bquote() is one way to have an object replaced by its value in an expression. You wrap the object you want replaced by its value in .( ). R will then look for the object and takes its value and insert it into the expression.

另请参阅 substitute() 以了解使用不同界面的替代方法.

See also substitute() for an alternative approach to this with a different interface.

这篇关于在绘图文本中使用表达式 - 打印变量的值而不是其名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆