r - 一根图例行中有多个希腊字母

标签 r label legend

我有以下一段 R 代码:

y1=rnorm(10,0,1)
y2=rnorm(10,0,1)
y3=rnorm(10,0,1)
x=seq(1,10,1)
mat=cbind(y1,y2,y3)
a=c(1,4,7)
b=c(2,5,8)
g=c(3,6,9)
v=as.factor(paste(expression(alpha)," = ",a,", ",
                  expression(beta)," = ",b,", ",
                  expression(gamma)," = ",g))
matplot(x,mat,type="l",col=1:3,lty=1,xlab="x",ylab="mat",main="Legend Practice")
legend("bottomright",col=1:3,lty=1,legend=levels(v))

在图例行中,对于与 3 个 y 值相对应的 3 行中的每一行,结果为“alpha = 1,beta = 2,gamma = 3”等。如何将其更改为 α = 1、β = 2、γ = 3 等等?

有什么想法吗?

最佳答案

我们可以使用bquote来实现

matplot(x,mat,type="l",col=1:3,lty=1,xlab="x",ylab="mat",main="Legend Practice")
legend("bottomright",col=1:3,lty=1, legend=as.expression(c(
        bquote(alpha~'='~.(a[1])~', '~beta~'='~.(b[1])~', '~gamma~'='~.(g[1])),
        bquote(alpha~'='~.(a[2])~', '~beta~'='~.(b[2])~', '~gamma~'='~.(g[2])),
        bquote(alpha~'='~.(a[3])~', '~beta~'='~.(b[3])~', '~gamma~'='~.(g[3])) )))

enter image description here

这可以通过循环遍历 @d.b 提到的向量序列来变得紧凑

legend("bottomright",col=1:3,lty=1, legend = as.expression(sapply(1:length(a),
  function(i) bquote(alpha~'='~.(a[i])~', '~beta~'='~.(b[i])~', '~gamma~'='~.(g[i])))))

或者使用maply

legend("bottomright",col=1:3,lty=1, legend = as.expression(mapply(function(x,y, z) 
       bquote(alpha~'='~.(x)~', '~beta~'='~.(y)~', '~gamma~'='~.(z)),
               a, b, g)))

关于r - 一根图例行中有多个希腊字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43311315/

相关文章:

java - 扩展类中的另一个方法可以修改标签吗?

r - 混淆矩阵错误: the data and reference factors must have the same number of levels

r - 距点一定距离内的点

ios - Swift 如何在标签中的文本周围添加背景颜色?

css - 单击标签不会单击 React 中的复选框?

r - R中多个图的通用图例

python - 通过 matplotlib 图例中的标记删除线

r - 图例不显示颜色

r - 如何在 'topicmodels' 中使用 : Check Frequency Weighting in a Term Document Matrix,

r - 提示用户无需等待