R语言 向分面数据添加公式与拟合曲线

来源:互联网 发布:王欣老婆捐钱知乎 编辑:程序博客网 时间:2024/05/06 16:25

数据


源代码:

library(ggplot2)data<-read.csv("D:\\rwork\\tiaocan_xiugai.csv",header = T)  #header = Falese的意思dt<-as.data.frame(data)dt2<-dt#函数lm_labels<-function(dat){  count1<-dat$count1  degree<-dat$degree  mod<-nls(count1 ~ a*degree^b, start = list(a=2, b= 1.5))  formula<-sprintf("italic(y)==%.3f*italic(x)^%.3f",                   round(coef(mod)[1],3),round(coef(mod)[2],3))  a=0  b=0  for(i in 1:15){    ymean=mean(count1)    a=a+(fitted(mod)[i]-ymean)^2    b=b+(count1[i]-ymean)^2  }  r=a/b  #r<-cor(dat$count1,dat$degree)  r2<-sprintf("italic(R^2)==%.3f",r)  data.frame(formula=formula,r2=r2,stringAsFactors=FALSE)}#载入包library(plyr)labels<-ddply(dt2,"fenlei2",lm_labels)labels$y<-c(31,39,49)labels$yr<-c(28,35,45)p<-ggplot(dt2,aes(x=dt$degree,y=dt$count1))+geom_point()+geom_smooth(method="nls",formula=y ~ a*x^b, start = list(a=2, b= 1.5),se=F)p<-p+facet_wrap(~fenlei2,nrow=1,scales="free_y")p<-p+geom_text(x=6,aes(label=formula,y=y),data=labels,parse=TRUE,hjust=0,size=8)p<-p+xlab("degree")+ylab("count")p<-p+geom_text(x=6.5,aes(label=r2,y=yr-1),data=labels,parse=TRUE,hjust=0,size=8)p+theme(strip.text=element_text(face="bold",size=rel(1.2)),        strip.background=element_rect(fill="lightblue",colour="black",size=1))

结果图:




0 0