library(gcookbook)
library(ggplot2)
#将基本绘图对象存储在对象sp中
sp<-ggplot(heightweight,aes(x=ageYear,y=heightIn)) #heightweight是gcookbook中的一个数据框集合
sp+geom_point()+stat_smooth(method = lm) #注意lm的l是L的小写(95%的置信域)
#geom_point()绘制散点图
#stat_smooth()函数设定method = lm向散点图中添加线性回归拟合线,这将调用Im()函数对数据拟合线性模型
#默认下,stat_smooth()函数会为回归拟合线添加95%的置信域
#置信域对应的置信水平通过level参数进行调整
#设定参数se=FALSE时,系统将不会对回归拟合线添加置信域
sp+geom_point()+stat_smooth(method = lm,level=0.99) #99%的置信域
sp+geom_point()+stat_smooth(method = lm,se=FALSE) #没有置信区间
#拟合线默认颜色是蓝色的,可以通过设定colour参数调整拟合线颜色
#也可以对拟合线的线型(linetype)和粗细(size)进行设置
#因为默认点是黑色,线要从蓝色变成黑色的话,不能突出直线
#可设置点的colour以使数据点不那么突出
sp+geom_point(colour="grey60")+stat_smooth(method = lm,se=FALSE,colour="black")
#这样就把点变成灰色的,线变成黑色的了
#method = lm是对数据拟合的线性模型,但是使用函数stat_smooth()的默认模型类型是拟合loess曲线,即不指定模型类型,则会拟合loess曲线(局部加权多项式)
sp+geom_point(colour="grey60")+stat_smooth(method = loess)
sp+geom_point(colour="grey60")+stat_smooth() #这两行命令输出的图形一样
| heightweight {gcookbook} | R Documentation |
Height and weight of schoolchildrenDescription[size=13.3333px]Height and weight of schoolchildren
Variables- sex
- ageYear: Age in years.
- ageMonth: Age in months.
- heightIn: Height in inches.
- weightLb: Weight in pounds.
Source[size=13.3333px]Lewis, T., & Taylor, L.R. (1967), Introduction to Experimental Ecology, Academic Press.
[size=13.3333px][Package gcookbook version 1.0 Index]