-->

答读者问~R语言ggplot2添加拟合曲线并给指定点添加注释

2021-02-20 10:38发布

• A 面积
• B 周长
• C紧凑度
• LK 长度
• WK 宽度
• A_coef 偏度系数
• LKG 腹沟长度

首先是读入数据
``seed <- read.csv("kaggle/Seed_Data.csv",header=T)names(seed) <- c("Area", "Perimeter", "Compactness", "Length", "Width", "Asymetry.coef", "Grove.length", "Type")head(seed)seed\$Type <- as.factor(seed\$Type)``
拟合方程
``fitted.model<-lm(Area~Perimeter,data = seed)summary(fitted.model)``

接下来是使用ggplot2画图

``library(ggplot2)ggplot()+  geom_point(data=seed,aes(x=Perimeter,y=Area),             size=5,color="red",alpha=0.3)+  geom_abline(intercept = fitted.model\$coefficients[[1]],              slope = fitted.model\$coefficients[[2]],              size=2,color="blue",alpha=0.8)+  theme_bw()``

接下来是添加辅助线

``ggplot()+  geom_point(data=seed,aes(x=Perimeter,y=Area),             size=5,color="red",alpha=0.3)+  geom_abline(intercept = fitted.model\$coefficients[[1]],              slope = fitted.model\$coefficients[[2]],              size=2,color="blue",alpha=0.8)+  theme_bw()+  geom_hline(yintercept = 15,lty="dashed")``
接下来算一下交点位置的坐标
``b<-fitted.model\$coefficients[[1]]a<-fitted.model\$coefficients[[2]]fitted.curve<-function(y){  return((y-b)/a)}fitted.curve(15)``
在这个交点添加一个点
``ggplot()+  geom_point(data=seed,aes(x=Perimeter,y=Area),             size=5,color="red",alpha=0.3)+  geom_abline(intercept = fitted.model\$coefficients[[1]],              slope = fitted.model\$coefficients[[2]],              size=2,color="blue",alpha=0.8)+  theme_bw()+  geom_hline(yintercept = 15,lty="dashed")+  geom_point(aes(x=fitted.curve(15),y=15),size=6,shape=17,             color="green",alpha=0.9)``
在交点位置向下添加垂直线段
``ggplot()+  geom_point(data=seed,aes(x=Perimeter,y=Area),             size=5,color="red",alpha=0.3)+  geom_abline(intercept = fitted.model\$coefficients[[1]],              slope = fitted.model\$coefficients[[2]],              size=2,color="blue",alpha=0.8)+  theme_bw()+  geom_hline(yintercept = 15,lty="dashed")+  annotate(geom = "segment",x=fitted.curve(15),           xend = fitted.curve(15),y=15,yend = -Inf,           lty="dashed")+  geom_point(aes(x=fitted.curve(15),y=15),size=6,shape=17,             color="green",alpha=0.9)``
在X轴与垂直线段的交点处添加文字
``ggplot()+  geom_point(data=seed,aes(x=Perimeter,y=Area),             size=5,color="red",alpha=0.3)+  geom_abline(intercept = fitted.model\$coefficients[[1]],              slope = fitted.model\$coefficients[[2]],              size=2,color="blue",alpha=0.8)+  theme_bw()+  geom_hline(yintercept = 15,lty="dashed")+  annotate(geom = "segment",x=fitted.curve(15),           xend = fitted.curve(15),y=15,yend = -Inf,           lty="dashed")+  geom_point(aes(x=fitted.curve(15),y=15),size=6,shape=17,             color="green",alpha=0.9)+  annotate(geom = "text",x=fitted.curve(15),y=11,           label=round(fitted.curve(15),2),           vjust=6,color="red")+  coord_cartesian(clip = "off")``

Ta的文章 更多文章

0条评论