如何在从 r 中的循环获得的图中使用 annotation_custom 或其他函数打印上标

问题描述

我想打印表达式和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],"+",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]],y=0.91,family = "Times New Roman")))
}

p=list()
for (i in 1:5) {
p[[i]]=ggplot(Dabase[[i]],aes(Dabase[[i]][,Dabase[[i]][,1]))+
geom_point(size=1,color="firebrick")+
geom_abline(intercept=Dvcoe[i,slope=Dvcoe[i,colour="dodgerblue",lwd=1)+
theme_classic()+geom_smooth(method="lm",lwd=1)+
scale_x_continuous(expand = c(0,0.015))+
labs(x=paste(substr(Dvcoe$Formula[i],y=paste(substr(Dvcoe$Formula[i],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",size=7),axis.text.y = element_text(angle = 0,axis.title.y = element_text(angle = 0,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)
}

enter image description here

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)