简体   繁体   中英

Position of the legend

i would like to write a function with graphical output of original data regression and one for modified data. The original data regression should be an option. Moreover there should be legends in the graphs. And here is my problem: If i choose the option: orig.plot=FALSE, everything works ok. But when i choose the other option: orig.plot=TRUE, the position of my legends is not very satisfying.

# Generation of the data set

set.seed(444)

nr.outlier<- 10

x<-seq(0,60,length=150);
y<-rnorm(150,0,10);
yy<-x+y;
d<-cbind(x,yy)


# Manipulation of data:
ss1<-sample(1:nr.outlier,1) # sample size 1
sri1<-sample(c(1:round(0.2*length(x))),ss1) # sample row index 1
sb1<-c(yy[quantile(yy,0.95)<yy])# sample base 1
d[sri1,2]<-sample(sb1,ss1,replace=T) # manipulation of part 1

ss2<-nr.outlier-ss1 # sample size 2 
sri2<-sample(c(round(0.8*length(x)+1):length(x)),ss2) # sample row index 2
sb2<-c(yy[quantile(yy,0.05)>yy])# sample base 2
d[sri2,2]<-sample(sb2,ss2,replace=T) # manipulation of par 2



tlm2<-function(x,y,alpha=0.95,orig.plot=FALSE,orig.ret=FALSE){

m1<-lm(y~x)
res<-abs(m1$res)
topres<-sort(res,decreasing=TRUE)[1:round((1-alpha)*length(x))] # top alpha*n residuals
topind<-rownames(as.data.frame(topres)) # indices of the top residuals
x2<-x[-as.numeric(topind)] #
y2<-y[-as.numeric(topind)] # removal of the identified observations

m2<-lm(y2~x2)
r2_m1<-summary(m1)$'r.squared'
r2_m2<-summary(m2)$'r.squared'
if(orig.plot==TRUE){
    par(mfrow=c(2,1))
    plot(x,y,xlim=range(x),ylim=c(min(d[,2])-30,max(d[,2]+30)),main="Model based on original data")
    abline(m1$coef);legend("topleft",legend=bquote(italic(R)^2==.(r2_m1)),bty="n")
}
plot(x2,y2,xlim=range(x),ylim=c(min(d[,2])-30,max(d[,2]+30)),main="Model based on trimmed data")
abline(m2$coef);

legend("topleft",legend=bquote(atop(italic(R)^2==.(r2_m2),alpha==.(alpha))),bty="n")

return(if(orig.ret==TRUE){list(m1=m1,m2=m2)} else{m2})
}

tlm2(d[,1],d[,2])

tlm2(d[,1],d[,2],orig.plot=T)

Can anyone give me a hint?

Thank You in advance!

The problem is that atop is essentially a division (ie x/y) without plotting the division bar. It also centers the denominator. The solution is to use expression instead of bquote . However, to mix expressions and variables, you need to use substitute and eval :

Here's what your legend call should look like:

legend("topleft",legend=c(eval(substitute(expression(italic(R)^2==my.r2), list(my.r2 = r2_m2))) ,
                          eval(substitute(expression(alpha==my.alpha), list(my.alpha = alpha)))
                          )
                          ,bty="n")

And here's the result: 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM