简体   繁体   English

R Legend变量替代

[英]R Legend Variable Substitution

I always desire to have my R code as flexible as possible; 我一直希望我的R代码尽可能灵活。 at present I have three (potentially more) curves to compare based on a parameter delta, but I don't want to hardcode the values of delta anywhere (or even how many values if I can avoid it). 目前,我有3条(可能更多)曲线要根据参数delta进行比较,但是我不想在任何地方对delta的值进行硬编码(如果可以避免的话甚至要硬编码多少个值)。

I am trying to make a legend that involves both Greek and a variable substitution for the delta values, so each legend entry is of the form like 'delta = 0.01', where delta is Greek and 0.01 is determined by variable. 我试图制作一个图例,该图例既包含希腊语又包含变量的delta值替代,因此每个图例条目的格式均类似于'delta = 0.01',其中delta是希腊语,而0.01由变量确定。 Many different combinations of paste , substitute , bquote and expression have been tried, but always end up with some verbatim code leftover in the finished legend, OR fail to put 'delta' into symbolic form. 尝试了pastesubstitutebquoteexpression许多不同组合,但是最终总是在完成的图例中bquote一些逐字代码,或者无法将“ delta”放入符号形式。

delta <- c(0.01,0.05,0.1)
plot(type="n", x=1:5, y=1:5) #the curves themselves are irrelevant
legend_text <- vector(length=length(delta)) #I don't think lists work either
for(i in 1:length(delta)){
  legend_text[i] <- substitute(paste(delta,"=",D),list(D=delta[i]) )
}
legend(x="topleft", fill=rainbow(length(delta)), legend=legend_text)

Since legend=substitute(paste(delta,"=",D),list(D=delta[1]) works for a single entry, I've also tried doing a 'semi-hardcoded' version, fixing the length of delta: 由于legend=substitute(paste(delta,"=",D),list(D=delta[1])适用于单个条目,因此我也尝试过使用“半硬编码”版本,固定了增量的长度:

legend(x="topleft", fill=rainbow(length(delta)),
       legend=c(substitute(paste(delta,"=",A), list(A=delta[1])),
                substitute(paste(delta,"=",B), list(B=delta[2])),
                substitute(paste(delta,"=",C), list(C=delta[3])) )
      )

but this has the same issues as before. 但这和以前有同样的问题。

Is there a way I can do this, or do I need to change the code by hand with each update of delta? 有没有办法做到这一点,还是我需要在每次更新增量时手动更改代码?

Try using lapply() with as.expression() to generate your legend labels. 尝试将lapply()as.expression()以生成图例标签。 Also use bquote to create your individual expressions 还可以使用bquote来创建您自己的表达式

legend_text <- as.expression(lapply(delta, function(d) {
    bquote(delta==.(d))
} ))

Note that with plotmath you need == to get an equals sign. 请注意,使用plotmath时,需要==才能得到等号。 Also no need for paste() since nothing is really a string here. 也不需要paste()因为这里的字符串实际上不是字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM