R中的希腊字母

Pat*_* Li 3 expression r legend

我希望在不同参数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)
Run Code Online (Sandbox Code Playgroud)

在图例中,我希望有三行alplha = 1,alpha = 2,alpha = 3.如何使其正确? 在此输入图像描述

luk*_*net 6

更好的循环答案来自这里和user20650.

解决方案与sapply

expression函数非常棘手,但与substitute您一起使用sapply可以循环:

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)
Run Code Online (Sandbox Code Playgroud)

简单修复

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)
Run Code Online (Sandbox Code Playgroud)