2013-03-08 54 views
2

我试图在R图中生成一个美丽的图例。我有一个factor=1e-5,应该很好地显示在图例中的格式。我在包sfsmisc中发现了一个很好的功能,它将数字转换为表达式。要将这个表达式添加到我的bquote命令中,似乎需要将它转换为一个调用。不幸的是,在字符串的末尾添加了大括号(10^-5())。用指数变换数字来绘制R中美丽的图例的命令

有没有办法避免添加大括号?还是有更简单的方法来将数字转换为plotmaths命令以供它们在图例中使用? (没有做手工)

factor = 1e-5 
alpha = 1:10 
omega = alpha^2 * factor 

plot (
    alpha 
    , omega 
    , xlab=bquote(alpha) 
    , ylab=bquote(omega) 
    , type="b" 
) 

text = expression() 

# standard version 
text[1] = as.expression(bquote(alpha%*%.(factor))) 

# beautified version (use pretty10exp from sfsmisc package!?) 
library("sfsmisc") 
pretty = as.call(pretty10exp(factor, drop.1=T)) 
text[1] = as.expression(bquote(alpha^2%*%.(pretty))) 

# add legend 
legend("topleft", legend=text, pch=1, lty=1) 

screenshot: red arrow points at the braces that should not be there

回答

3

这里是你,而不是做什么用功能parse

text <- paste("alpha^2%*%",parse(text=pretty10exp(factor,drop.1=T)),sep="") 
text 
[1] "alpha^2%*%10^-5" # which we then use as the expression in your call to legend 
legend("topleft", legend=parse(text=text), pch=1, lty=1) 

?parse更多解释这是如何工作的。

+0

不错的解决方法,...我认为有更简单的方法。无论如何,首先生成plotmath命令,然后解析它,仍然很直观,... – 2013-03-08 11:13:33

+0

是的,我试图找到一种方法来直接连接两个表达式(一个与alpha和pretty10exp输出),但不能不需要像这里那样建立一个字符串作为前面的步骤。 – plannapus 2013-03-08 11:18:06