Mike T
Mike T

Reputation: 43642

How to combine expressions for multiple items in a legend?

I can't seem to build a legend mixing text and expressions. I need to use bquote to put a value in an expression, but I can't seem to concatenate it with text for another item in a legend. For example:

legend_text <- "text"
beta <- 0.01  # this is a variable
if (beta > 0)
    legend_text = c(bquote(beta == .(beta)), legend_text)

plot(1, type="n")
legend("topright", legend=legend_text, text.col="red")  # doesn't work for two items
legend("bottomright", legend=bquote(beta == .(beta)), text.col="blue") # works as expected

enter image description here

Any ideas to mix two items to get the expected result?

Upvotes: 2

Views: 396

Answers (1)

Rorschach
Rorschach

Reputation: 32426

Perhaps passing the whole as an expression will work

plot(1, type="n")
legend("topright", legend=as.expression(legend_text), text.col="red")
legend("bottomright", legend=bquote(beta == .(beta)), text.col="blue") # works as expected

enter image description here

Upvotes: 3

Related Questions