How to combine character (or numeric) variables with expressions in LEGEND in R

When using R to build three lines with a legend that combines expressions and character variables, I wrote, for example:

b1<-2 c1<-3 d1<-4 a<-seq(1,10) b<-a+b1 c<-a+c1 d<-a+d1 plot(NA ,axes = FALSE ,xlim=c(0,10) ,ylim=c(0,15) ) box() lines(a,b,col=1) lines(a,c,col=2) lines(a,d,col=3) legend(8,2 ,c(expression(paste(italic(b)[1],"=2","m")) ,expression(paste(italic(c)[1],"=3","m")) ,expression(paste(italic(d)[1],"=4","m")) ) ) 

The above scripts give exactly the legend I want. However, the values โ€‹โ€‹of b1, c1 and d1 are hardcoded in the script.

Is there a way to put the variables b1, c1 and d1 in a legend script? I tried many ways, for example

no1.

 b2<-as.character(b1) legend(6,2 ,c(expression(paste(italic(b)[1],b2,"m")) ,expression(paste(italic(c)[1],"=3","m")) ,expression(paste(italic(d)[1],"=4","m")) ) ) 

NO2.

 legend(4,2 ,c(bquote(paste(italic(b) [1], "=",.(b1),"m" )) ,expression(paste(italic(c)[1],"=3","m")) ,expression(paste(italic(d)[1],"=4","m")) ) ) 

this one works for the first line, but if I do three lines on bquote, this no longer works:

 legend(2,2 ,c(bquote(paste(italic(b) [1], "=",.(b1),"m" )) ,bquote(paste(italic(b) [1], "=",.(b1),"m" )) ,bquote(paste(italic(b) [1], "=",.(b1),"m" )) ) ) 

Any great ideas? Thank you very much in advance!

+4
source share
2 answers

Try something like this:

 lgnd <- c(bquote(italic(b)[1] == .(b1)*m), bquote(italic(c)[1] == .(c1)*m), bquote(italic(d)[1] == .(d1)*m)) legend(2,4, as.expression(lgnd)) 
+5
source

I think this should give you what you want, right?

 leg<-as.factor(paste("m =",c(b1,c1,d1))) legend("bottomright", levels(leg), lwd=1, lty=1, col=c(1,2,3), cex=1.25) 

Perhaps I misunderstood the lines and levels of legends, it's up to you to fix this !;)

0
source

Source: https://habr.com/ru/post/1488059/


All Articles