Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Greek letters in legend in R

I want to have three curves on the same plot with different parameter alpha.

curve(sin(x), from = 1, to = 3, lty = 1, ylim = c(-1, 1))
curve(sin(2 * x), add = TRUE, lty = 2)    
curve(sin(3 * x), add = TRUE, lty = 3)
legend("topright", legend = expression(paste(alpha, " = ", c(1, 2, 3))), lty = 1:3)

In the legend, I want to have three lines with alplha = 1, alpha = 2, alpha = 3. How do I make it correct? enter image description here

like image 770
JACKY Li Avatar asked Mar 15 '23 21:03

JACKY Li


1 Answers

The better, looped answer comes from here and user20650.

Solution with sapply

The expression function is quite tricky but in conjunction with substitute you can use sapply to loop:

curve(sin(x), from = 1, to = 3, lty = 1, ylim = c(-1, 1))
curve(sin(2 * x), add = TRUE, lty = 2)    
curve(sin(3 * x), add = TRUE, lty = 3)
legend("topright",
       legend = sapply(1:3, function(x) as.expression(substitute(alpha == B,
                                                                 list(B = as.name(x))))),
       lty = 1:3)

Simple Fix

curve(sin(x), from = 1, to = 3, lty = 1, ylim = c(-1, 1))
curve(sin(2 * x), add = TRUE, lty = 2)    
curve(sin(3 * x), add = TRUE, lty = 3)
legend("topright", legend = c(expression(paste(alpha, " = ", 1)),
                              expression(paste(alpha, " = ", 2)),
                              expression(paste(alpha, " = ", 3))), lty = 1:3)
like image 173
luke.sonnet Avatar answered Mar 18 '23 14:03

luke.sonnet