0

我想打印表达式和 r 平方;但是获取 r squared 文本的方式是不合适的。我正在使用列表或多个线性模型,并且使用 annotation_custom 我可以毫无问题地找到文本。

下面是我的代码示例:

j=c("ggplot2","grid","stringi","data.table")
lapply(j,require,character.only=TRUE)

set.seed(4321)
V=sample(1:1800,100,replace=FALSE);sort(V)
e=runif(15,0.66,0.8)
s=runif(15,0.77,0.92)
Dabase=list()

for (i in 1:5){
Dabase[[i]]=data.frame(x=round(V*e[i]),y=round(V*s[i]))
}

lms=list();s=list();NCoef=list();Coef=list()
for(i in 1:5){ 
lms[[i]]=(lm(y~x,Dabase[[i]]))   
s[[i]]=summary(lms[[i]])   
NCoef[[i]]=names(lms[[i]]$coefficients)
Coef[[i]]=signif(as.numeric(lms[[i]]$coefficients),digits=3) 
}

Dvcoe <- as.data.frame(t(stri_list2matrix(Coef)))
colnames(Dvcoe)=c("Intercept",paste(rep(("VarCoef"),(dim(Dvcoe)[2]-1)),
seq(1:(dim(Dvcoe)[2]-1)),sep="_"))
Dvcoe$Formula=rep("y~x",5)

label=list();grob1=list();grob2=list()
for (i in seq_along(Dabase)){ 
grob1[[i]]=grobTree(textGrob(paste(substr(Dvcoe$Formula[i],1,1),"=",Dvcoe[i,1],"+",Dvcoe[i,2],"*",substr(Dvcoe$Formula[i],3,3)), x=0.01,  y=0.95, hjust=0,gp=gpar(col="black", fontsize=5,colour="black",fontface="plain",family = "Times New Roman")))
}

for (i in seq_along(s)){
label[[i]]=paste("r^2==", s[[i]]$r.squared)
grob2[[i]]=grobTree(textGrob(label[[i]], x=0.01,  y=0.91, hjust=0,
                           gp=gpar(col="black", fontsize=5,colour="black",fontface="plain",family = "Times New Roman")))
}

p=list()
for (i in 1:5) {
p[[i]]=ggplot(Dabase[[i]],aes(Dabase[[i]][,2],Dabase[[i]][,1]))+
geom_point(size=1,color="firebrick")+
geom_abline(intercept=Dvcoe[i,1], slope=Dvcoe[i,2],colour="dodgerblue",lwd=1)+
theme_classic()+geom_smooth(method="lm",colour="dodgerblue",lwd=1)+
scale_x_continuous(expand = c(0,0.015))+
labs(x=paste(substr(Dvcoe$Formula[i],3,3)), y=paste(substr(Dvcoe$Formula[i],1,1)))+theme(text= element_text(size=7, family = "Times New Roman", color="black"),
                                                   axis.text.x = element_text(angle = 0,hjust=0.5, vjust = 0.5, face="plain", colour="black",size=7),
                                                   axis.text.y = element_text(angle = 0,hjust=0.5, vjust = 0.5, face="plain",colour="black",size=7),
                                                   axis.title.y = element_text(angle = 0,hjust=0.5, vjust = 0.5, face="plain",colour="black"))
p[[i]] + annotation_custom(grob1[[i]])+
annotation_custom(grob2[[i]])
ggsave(filename=paste0("C:/Users/Desktop/Trying/lm",rownames(Dvcoe)[i],".tiff"), 
     last_plot(),device="tiff",width= 10, height= 7,units="cm",dpi=600)
}

在此处输入图像描述

4

0 回答 0