2

I want to add a legend to a plot in which only one of the legend names is italicized. I'm using plot() in base R.

  • However, I need that italicized line to contain variable numbers, so I use bquote.

What I've tried does not work:

  a <- 2 ; b <- 5
  plot(a,b)
  l1 <- bquote(Italic ~ .(a) + .(b))
  l2 <- bquote(a + b)
  legend(x='topright',legend = bquote(italic(.(l1))))
  legend(x='topleft',legend = c(bquote(italic(.(l1))),l2))
  • Notice that when I leave the expression on its own (RIGHT LEGEND), it italicizes correctly. However, when I add the text for other legend lines, it messes up (LEFT LEGEND).

enter image description here

How do I properly do this?

Note: I'd rather have a solution that doesn't require multiple calls to legend().

theforestecologist
  • 4,667
  • 5
  • 54
  • 91

2 Answers2

3

You should use as.expression to coerce everything into an expression object.

a <- 2
b <- 5
plot(a,b)
legend("topleft", legend = c(as.expression(bquote(italic("Italic: "*.(a)*" + "*.(b)))),
    as.expression(bquote("Non Italic: "*.(a)*" + "*.(b)))) )

To modify your example

a <- 2
b <- 5
plot(a,b)
l1 <- bquote(Italic ~ .(a) + .(b))
l2 <- bquote(a + b)
legend("topleft", legend =  c(as.expression(bquote(italic(.(l1)))),
                            as.expression(bquote(.(l2))) ))
d.b
  • 32,245
  • 6
  • 36
  • 77
2

You could use text.font = 3, say:

legend(x='topleft',legend = c(bquote((.(l1))),l2), text.font=c(3,1))
Edgar Santos
  • 3,426
  • 2
  • 17
  • 29
  • 1
    then use text.font=c(3,1) to specify what line you want italicized. edited on my answer. Even text.font=c(3, NA) works well. – Edgar Santos Mar 28 '17 at 21:00
  • great! Your edited solution does the trick! Thanks! I will wait to see if others propose any ideas the rest of the evening but will accept your solution if no one does. – theforestecologist Mar 28 '17 at 21:07