komodovaran_
komodovaran_

Reputation: 2012

Plot legend with subscript and insert stored value in R

Trying to add a legend to my plot, which should display some fitting parameters I've calculated earlier, subscripts AND a new line for every parameter, but I can't seem to make a legend that works with e.g. substitute() and paste() together. legend() always seems to break with a argument "legend" is missing, with no default. Apparently substitute() can't do new lines, and mtext() is a bit... bothersome, compared to the human-readable "bottomright" parameter in legend().

This is as far as I've gotten:

paramX = 1234
paramY = 9876

plot.new()

legend("bottomright",
       bty = "n",
       paste("x[max] = ", paramX,
             "\ny[max] = ", paramY)
)

Upvotes: 0

Views: 1292

Answers (1)

Roland
Roland

Reputation: 132969

paramX = 1234
paramY = 9876

plot.new()

expr <- vector("expression", 2)
expr[[1]] <- bquote(x[max]==.(paramX))
expr[[2]] <- bquote(y[max]==.(paramY))

legend("bottomright",
       bty = "n",
       legend = expr)

Plots this result:

resulting plot

Relevant documentation: help("legend"); help("plotmath"); help("bquote").

The most difficult part is combining two bquote expressions into one expression vector.

Upvotes: 3

Related Questions