LOFTER for ipad —— 让兴趣,更有趣

点击下载 关闭
R语言-ggplot2包绘制散点图

散点图通常用来刻画两个连续变量之间的关系。

基本散点图

geom_point()函数,分别映射一个变量x和y

数据:

library(gcookbook)

heightweight

ggplot(heightweight,aes(x=ageYear,y=heightIn))+geom_point()

我们可以设置点的形状(shape)大小(size)颜色(col)

ggplot(heightweight,aes(x=ageYear,y=heightIn))+geom_point(size=1.5,shape=21,col="blue")

系统默认:size=2,shape=16,col=“black”

我们可以使用点的颜色,形状,基于某变量对点进行分类。

数据:

library(gcookbook)

heightweight

ggplot(heightweight,aes(x=ageYear,y=heightIn,col=sex))+geom_point()

ggplot(heightweight,aes(x=ageYear,y=heightIn,shape=sex))+geom_point()

注意:分组变量必须是分类变量,所以它必须是因子型或者字符型的额变量。如果分组变量是数值型变量,我们必须将它转化成因子型后进行操作。

我们还可以将一个变量同时映射个shape和col属性。

ggplot(heightweight,aes(x=ageYear,y=heightIn,shape=sex,col=sex))+geom_point()

当散点图模型的图形不是你喜欢的,你可以通过scale_shape_manual()函数和

scale_colour_brewer()函数来调节。

ggplot(heightweight,aes(x=ageYear,y=heightIn,shape=sex,col=sex,shape=sex))+geom_point()+scale_shape_manual(values=c(1,2))+scale_colour_brewer(palette = "Set1")

添加回归模型拟合线

方法:运行stat_smooth()函数,并设定method=lm。

sp<-ggplot(heightweight,aes(x=ageYear,y=heightIn))

sp+geom_point()+stat_smooth(method = lm)


sp<-ggplot(heightweight,aes(x=ageYear,y=heightIn))

sp+geom_point()+stat_smooth(method = lm,levels=0.99,col="black")

sp+geom_point()+stat_smooth(method = lm,se=FALSE)

百分之九十九的置信区间和没有置信区间。可以设置拟合线的颜色。


推荐文章
评论(0)
分享到
转载我的主页