R语言绘图——散点图(一)

一 绘制基本的散点图

> ggplot(heightweight,aes(x=ageYear,y=heightIn))+geom_point()
;;从heightweight里面选出年龄和身高

R语言绘图——散点图(一)

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

 R语言绘图——散点图(一)

 

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

R语言绘图——散点图(一)

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

 R语言绘图——散点图(一)

 

二 使用不同于默认设置的点形

> ggplot(heightweight,aes(x=ageYear,y=heightIn,shape=sex))+
+ geom_point(size=3)+
+ scale_shape_manual(values=c(1,4))   ;;通过该命令修改point的形状

 R语言绘图——散点图(一)

R语言绘图——散点图(一)

 点1-20的颜色都可以由color参数来控制;对于点21-25而言,实心区的颜色由color和fill控制

 

> hw <- heightweight
> hw$weightGroup <- cut(hw$weightLb,breaks=c(-Inf,100,Inf),labels=c("<100",">=100"))
> ggplot(hw,aes(x=ageYear,y=heightIn,shape=sex,fill=weightGroup))+
+ geom_point(size=2.5)+
+ scale_shape_manual(values=c(21,24))+
+ scale_fill_manual(values=c("NA","black"),guide=guide_legend(override.aes = list(shape=21)))
;;
把sex映射给shape
把weightgroup映射给fill
通过scale命令调整shape和fill映射的值

R语言绘图——散点图(一)

三 将连续变量映射到点的颜色或大小上 

 

> library(gcookbook)
> heightweight[1:5,c("sex","ageYear","weightLb")]
  sex ageYear weightLb
1   f   11.92     85.0
2   f   12.92    105.0
3   f   12.75    108.0
4   f   13.42     92.0
5   f   15.92    112.5
> ggplot(heightweight,aes(x=ageYear,y=heightIn,color=weightLb))+geom_point()
> ggplot(heightweight,aes(x=ageYear,y=heightIn,size=weightLb))+geom_point() ;;还可以加上sclae_size_continuous(range=c(2,5))来调节点的大小范围

;;将weightLb分别映射给color和size

R语言绘图——散点图(一)

R语言绘图——散点图(一)

 

>ggplot(heightweight,aes(x=ageYear,y=heightIn,fill=weightLb))+geom_point(shape=21,size=2.5)+scale_fill_gradient(low="black",high="white")

R语言绘图——散点图(一)

> ggplot(heightweight,aes(x=ageYear,y=heightIn,fill=weightLb))+
+ geom_point(shape=21,size=2.5)+
+scale_fill_gradient(low="black",high="white",breaks=seq(70,170,by=20),guide=guide_legend())

;;通过scale_fill+gradient()可以调整颜色层级和数据间隔

R语言绘图——散点图(一)

> ggplot(heightweight,aes(x=ageYear,y=heightIn,size=weightLb,color=sex))+
+ geom_point(alpha=.5)+
+ scale_size_area()+                      ;;使数据点正比于变量值
+ scale_color_brewer(palette="Set1")

> ggplot(heightweight,aes(x=ageYear,y=heightIn,size=weightLb,color=sex))+
+ scale_color_brewer(palette="Set1")+
+ geom_point(alpha=.5)                       ;;非正比

R语言绘图——散点图(一)R语言绘图——散点图(一)