Saïd Maanan
Saïd Maanan

Reputation: 697

Use expression() inside a matrix to create a legend in R

In an experiment I am running, the plot legend is created as follows:

eigenvalues <- t(c(1,2))
plot(1)
# Legend
legend_text <- cbind(
  paste("λ1 =", eigenvalues[, 1]),
  paste("λ2 =", eigenvalues[, 2])
)
legend("topright", legend = legend_text, text.col = "black", bty = "n", cex = 1)

enter image description here

However, instead of "λ1 =" I would like to use lambda[1], but when I use it I get the following error:

legend_text <- cbind(
  expression(lambda[1] == eigenvalues[, 1]),
  expression(lambda[2] == eigenvalues[, 2])
)

Error in cbind(expression(lambda[1] == eigenvalues[, 1]), expression(lambda[2] ==  : 
  cannot create a matrix from type 'expression'

How do I use expression(lambda[1] for the legend without getting an error message?

Upvotes: 1

Views: 66

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 270195

Create a vector of legend strings, legend_str, and then convert each element to a language object:

eigenvalues <- 1:2
lambda <- c("lambda[1]", "lambda[2]")

plot(1)

legend_str <- paste(lambda, "==", eigenvalues)
legend("topright", legend = lapply(legend_str, str2lang), bty = "n")

screenshot

Upvotes: 1

Roland
Roland

Reputation: 132969

In order to use plotmath parsing, you need to provide expressions:

legend_text <- lapply(1:2, \(j) bquote(lambda[.(i)] == .(e), 
                                       list(i = j, e = eigenvalues[, j])))

Upvotes: 3

Related Questions