JavierM88 JavierM88 - 1 month ago 3
R Question

Legend in two rows in R using bquote

I want to plot the legend using

bquote
, but I have a problem adding two rows in my legend. For example:

This works:

plot(1:10)
r2=0.99
legend("topleft",legend=bquote(R^{2} ~ "=" ~.(r2)),bty = "n")


enter image description here

But if I add a second row:

plot(1:10)
r2=0.99
pval=0.01
legend("topleft",legend=c(bquote(R^{2} ~ "=" ~.(r2)),paste("P-value =",pval)),bty = "n")


The whole first element of my vector in legend is "expanded". Why is that?

enter image description here

42- 42-
Answer

It's because c-function cannot concatenate multiple instances of the object type returned by bquote. Most people think that bquote returns R expressions, but it does not. It returns calls and they don't concatenate into lists. You need to apply the expression function to items returned by multiple calls to bquote to get them into an 'expression'-list. This was explained by Thomas Lumley on Rhelp in 2005:

legend("topleft",legend=do.call( 'expression', 
                                list( bquote( R^{2} == .(r2)), 
                                      bquote( "P-value" == .(pval)))  ),
                  bty = "n")

enter image description here

Comments