上文的主要内容是,用连续变量显示分类变量分布时可以采用折线图(
geom_freqpoly()
),而当用分类变量显示连续变量时,可以采用箱线图(geom_boxplot()
),本文介绍描述两个分类变量和两个连续变量相关变动时的可视化情况。
两个分类变量
利用diamonds数据集中的两个分类变量,cut和color,计算出每个变量组合中的观测数量,采用geom_count()
函数:
library(ggplot2)
ggplot(diamonds,aes(cut,color))+geom_count()
每个圆点的大小表示每个变量组合中的观测数量。
计算观测数量的方法,我们可以使用dplyr:
library(dplyr)
diamonds %>% count(cut,color)
# A tibble: 35 x 3
cut color n
<ord> <ord> <int>
1 Fair D 163
2 Fair E 224
3 Fair F 312
4 Fair G 314
5 Fair H 303
6 Fair I 175
7 Fair J 119
8 Good D 662
9 Good E 933
10 Good F 909
# ... with 25 more rows
接着利用得到的数据,使用geom_tile()
函数填充图形属性:
diamonds %>% count(cut,color) %>% ggplot(aes(color,cut))+geom_tile(aes(fill=n))
两个连续变量
对于两个连续变量间的相关变动表示,可以使用geom_point()
画出散点图。例如,描述钻石克拉数和价值之间的关系:
ggplot(diamonds,aes(carat,price))+geom_point()
随着数据规模的不断扩大,散点图的作用会越来越小,出现过绘制(散点堆叠),为了解决这个问题,可以设置透明度alpha:
ggplot(diamonds)+geom_point(aes(carat,price),alpha=1/100)
但是很难对于特别大的数据集设置透明度。另一种解决方案是分箱。之前使用了
geom_histogram()
和geom_freqpoly()
函数在一个维度上分箱。现在使用geom_bin2d()
和geom_hex()
在两个维度上分箱。geom_bin2d()
和geom_hex()
函数将坐标平面分为二维分箱,并使用一种填充颜色表示落入每个分箱的数据点。geom_bin2d()
创建长方形分箱,geom_hex()
创建六边形分箱。如果使用geom_hex()
需安装hexbin包:
smaller <- diamonds %>% filter(carat<3)
ggplot(smaller)+geom_bin2d(aes(carat,price))
#install.packages('hexbin')
ggplot(smaller)+geom_hex(aes(carat,price))
另一个方式是对一个连续变量分箱。例如,对carat进行分箱,为每组生成一个箱线图:
ggplot(data = smaller, mapping = aes(x = carat, y = price)) +geom_boxplot(mapping = aes(group = cut_width(carat, 0.1)))
近似的显示每个分箱中数据点的数量,可以使用
cut_number()
函数:
ggplot(data = smaller, mapping = aes(x = carat, y = price)) +
geom_boxplot(mapping = aes(group = cut_number(carat, 20)))