Greek letters with legend
I'm trying to get Greek letters to appear in a legend command. I've tried all different ways to use "text" and "expression", but it doesn't work. Here is the code.
plot(density(R1[,1,2]),ylim=c(0,1),
xlab="Correlation",main="",lty=1)
lines(density(R2[,1,2]),lty=2)
lines(density(R3[,1,2]),lty=3)
legend("topright", title="Values for eta",lty=1:3,cex=.8,
c("eta=1","eta=2","eta=3"))
Thanks for your consideration.
You need to pass an expression vector for the labels. Character vectors are interpreted as literal text, which is not what you want.
We typically use expression
, str2expression
, or parse
to construct expression vectors, depending on context. expression
isn't vectorized, so it is less useful when programming but fine in simple cases like yours.
Here are three examples producing identical plots:
plot(1:10
legend("topleft", legend = expression(paste(alpha, " = ", 1), paste(beta, " = ", 2), paste(gamma, " = ", 3)), lty = 1:3)
plot(1:10)
legend("topleft", legend = str2expression(paste(c("alpha", "beta", "gamma"), "* \" = \" *", 1:3)), lty = 1:3)
plot(1:10)
legend("topleft", legend = parse(text = paste(c("alpha", "beta", "gamma"), "* \" = \" *", 1:3)), lty = 1:3)
I would construct your labels like so:
str2expression(paste("eta * \"=\" *", 1:3))
You'll find even more examples in ?plotmath
and the respective function help pages. ?plotmath
in particular documents the special syntax used by graphics devices to typeset labels given as expressions.