当数据点重叠很严重时,用散点图来观察变量关系就显得力不从心了。下面是一个人为设计的例子,其中10000个观测点分布在两个重叠的数据群中:
>set.seed(1234)
>n<-10000
>c1<-matrix(rnorm(n,mean = 0,sd=.5),ncol=2)
>c2<-matrix(rnorm(n,mean = 3,sd=2),ncol=2)
>mydata<-rbind(c1,c2)
>mydata<-as.data.frame(mydata)
>names(mydata)<-c("x","y")
>with(mydata,plot(x,y,pch=19,main="Scatter Plot with 10,000 Observations"))
数据点的重叠导致识别x与y间的关系变得异常困难,针对这种情况,R提供了一些解决办法,你可以使用封箱、颜色和透明度来指明途中任一点上重叠点的数目。
smoothScatter()函数可利用核密度估计生成颜色密度来表示点分布的散点图,代码如下:
>with(mydata,smoothScatter(x,y,main="Scatterplot Colored by Smoothed Densities"))
hexbin包中的hexbin()函数将二元变量的封箱放到六边形单元格中,代码如下:
IDPmisc包中的iplot()函数也可以通过颜色来表示点的密度,代码如下:
> library(IDPmisc)
> with(mydata,iplot(x,y,main = "Image Scatter Plot with Color Indicating Density"))
综上可见,基础包中的smoothScatter()函数,hexbin包中的hexbin()函数,以及IDPmisc包中iplot()都可以读大数据集创建可读性较好的高密度散点图。