本讲将进一步介绍ggplot2绘制更加复杂的散点图,包括二维密度估计散点图、椭圆散点图、带有矩形箱的散点图、具有边际密度分布图的散点图,以及自定义散点图。
1. 查看数据head(faithful)
输出结果:
eruptions waiting1 3.600 792 1.800 543 3.333 744 2.283 625 4.533 856 2.883 55
2. 二维密度估计的散点图
可以使用函数geom_density_2d()或stat_density_2d():
#二维密度估计点散点图sp<- ggplot(faithful, aes(x=eruptions, y=waiting))+geom_point()sp+ geom_density_2d()#梯度颜色sp+ stat_density_2d(aes(fill = ..level..), geom="polygon")#更改梯度颜色sp+ stat_density_2d(aes(fill = ..level..), geom="polygon")+scale_fill_gradient(low="blue", high="red")
3. 椭圆散点图
函数stat_ellipse()可以按以下方式使用:
#在所有点外作一个椭圆ggplot(faithful, aes(waiting, eruptions))+geom_point()+stat_ellipse()#根据组别作椭圆p3))+geom_point()p+ stat_ellipse()#更改椭圆点形状,type可选值为:"t","norm", "euclid",默认值“ t”假设数据为多元t分布,“norm”假设多元正态分布。“ euclid”表示画一个半径等于一定水平的圆,代表距中心的距离。除非应用coord_fixed(),否则该椭圆不会显示为圆形。p + stat_ellipse(type ="norm")