14

Following works, (copy & paste into R)

a=123
plot(1,1)
legend('bottomleft',legend=bquote(theta == .(a)))

I want to have multiple items in the legend. All with greek letters. As a simple example, if I repeat the item twice the code does not work anymore

a=123
plot(1,1)
legend('bottomleft',legend=c(bquote(theta == .(a)),bquote(theta == .(a))))

I have tried many more complicated expressions but they all did not work.

Any help will be appreciated.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Sang
  • 535
  • 5
  • 14

2 Answers2

20

In this case, plotmath is not able to coerce the list of calls to expressions.

> cs <- c(bquote(theta == .(a)),bquote(theta == .(a)))
> cs
[[1]]
theta == 123

[[2]]
theta == 123

> sapply(cs, class)
[1] "call" "call"

You can make this work if you coerce to expressions yourself:

> c(as.expression(bquote(theta == .(a))), as.expression(bquote(theta == .(a))))
expression(theta == 123, theta == 123)
> plot(1,1)
> legend('bottomleft',legend= c(as.expression(bquote(theta == .(a))), 
+                               as.expression(bquote(theta == .(a)))))

Another way is to coerce the original list of calls to expressions using sapply:

plot(1,1)
legend("bottomleft", 
       sapply(c(bquote(theta == .(a)), bquote(theta == .(a))), as.expression))
Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
  • 1
    @Gavin: I seem to remember a long exchange on Rhelp several years ago where Thomas Lumley finally came up with an sapply(..., as.expression) solution. I've tried to locate it without success on other occasions, but now I know where to find another copy :-) – IRTFM Aug 26 '11 at 22:05
1

To coerce the original list of calls to expressions it is not necessary to use sapply(). It suffices to use as.expression() only for one of the components within the c() construct:

plot(1,1)
legend("bottomleft", 
       c(as.expression(bquote(theta == .(a))), bquote(theta == .(a))))

c() will then automatically coerce the whole list, to the expression class.

Axeman
  • 32,068
  • 8
  • 81
  • 94
vladbazon
  • 11
  • 2