本文介绍了使用指数将数字转换为plotmath命令以获取R中的美丽图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在R图中生成一个美丽的图例.我有一个factor=1e-5,应该在图例中很好地显示了格式.我在包sfsmisc中找到了一个不错的函数,该函数可以将数字转换为表达式.要将此表达式添加到我的bquote命令中,似乎需要将其转换为调用.不幸的是,在字符串(10^-5())的末尾添加了括号.

I'm trying to generate a beautiful legend in R plots. I have a factor=1e-5, that should appear nicely formatted in the legend. I found a nice function in the package sfsmisc, that transforms numbers to expressions. To add this expression to my bquote command, it seems that I need to transform itto a call. unfortunately, there are braces added at the end of the string (10^-5()).

有没有一种方法可以避免添加那些括号?还是有一种更简单的方法将数字转换为plotmaths命令以用于图例中? (无需手动执行)

Is there a way to avoid the addition of thoses braces? Or is there even an easier way to transform numbers to plotmaths commands for their use in legends? (without doing it manually)

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)

推荐答案

您可以使用功能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.

See ?parse for more explanation on how this work.

这篇关于使用指数将数字转换为plotmath命令以获取R中的美丽图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 13:48