R图中传说中的标题位置

时间:2015-02-28 21:56:28

标签: r plot legend

我使用以下代码绘制图表。

x = seq(-20,20,by=0.2);
c = .2;
y1 = exp(c*x);
c = .5;
y2 = exp(c*x);
c = 1;
y3 = exp(c*x);
par(mgp = c(2,.5,0));   # to adjust dist of x/y label to plot, x/y axes to plot
plot(x,
     y1,
     type="l",
     xlab=expression(x-theta),
     ylab=expression(L(x,theta)),
     main="function");
lines(x,y2,col="blue");
lines(x,y3,col="green");
legend(x=-20,
       y=40,
       title=expression(L(x, theta)==e^{c(x-theta)}),
       legend=expression("c=.2", "c=.5", "c=1"),
       lty=c(1, 1, 1),
       lwd=c(2.5, 2.5,2.5),
       col=c("black","blue","green"));

我发现图例中$(x- \ theta)$的括号超出了框。有没有办法让这个表达下来?我尝试用

替换原始图例功能
legend(x=-20,y=40,title.adj=c(0,.5), title=expression(L(x,theta)==e^{c(x-theta)}), legend=expression("c=.2","c=.5","c=1"), lty=c(1,1,1), lwd=c(2.5,2.5,2.5), col=c("black","blue","green"));

但是,表达式在图例框中出现了两次。

谢谢!

1 个答案:

答案 0 :(得分:1)

我认为没有方框(legend( ... ,bty='n'))会更好看,但如果你真的想要一个方框,请按照以下方式进行操作:

lgnd = legend(x=-20,
               y=40,
               title=expression(L(x, theta)==e^{c(x-theta)}),
               legend=expression("c=.2", "c=.5", "c=1"),
               lty=c(1, 1, 1),
               lwd=c(2.5, 2.5,2.5),
               col=c("black","blue","green"),
               # no box
               bty='n');

# plot your own box using the lgnd$rect as your starting point
params = lgnd$rect
rect(xleft = params[['left']],
    ybottom = params[['top']] - params[['h']],
    xright = params[['left']] + params[['w']],
    ytop = params[['top']] + 1)