R语言-初识ggplot2
2018-09-03 本文已影响61人
PriscillaBai
因为做事情不喜欢拖拖拉拉,所以打算每次啃一章,一个月啃完这本书。
建立一个正式的语法系统包括:数据集,几何对象,映射集合,统计变换,位置调整,坐标系和分面。
ggplot2的核心思想是图层和映射
一 数据集
ggplot(data=mpg)
画出来的一片白,作用是将数据集载入。
二 几何对象
总结一下ggplot2的几种常用的集合对象,剩下的各种图形基本上都是在此基础的变化。如气泡图是点图的变化,饼状图是bar图的变化
geom_line | 线图 |
geom_point | 点图 |
geom_histogram | 柱状图 |
geom_boxplot | 箱线图 |
geom_bar | bar图 |
geom_smooth | 平滑曲线图 |
三 映射
将横轴和纵轴,按照几何对象的种类,映射到图形上,就完成了画图的主要过程。
- 散点图
ggplot(data=mpg)+geom_point(mapping=aes(x=displ,y=hwy))

想用不同的颜色代表分类,就多映射一个变量
ggplot(data=mpg)+geom_point(mapping=aes(x=displ,y=hwy,color=class))

四 统计变换
以条形图为例
ggplot(data=diamonds)+geom_bar(mapping=aes(x=cut))

我们并没有映射Y轴,但是为什么Y轴有数值呢?这是因为内部进行了统计变换
统计变换:stat(statistical transformation)
如果我们?geom_bar,就会发现:

stat的默认值是count,也就是计数。也就是说,geom_bar内部是做过统计变换的,用的方法是count。
如果将geom_point换成stat_count
ggplot(data=diamonds)+stat_count(mapping=aes(x=cut))

我们会发现,画出的图形是一样的。
五 位置调整
a<-ggplot(diamonds)+geom_bar(mapping=aes(x=cut,color=cut))
b<-ggplot(diamonds)+geom_bar(mapping=aes(x=cut,fill=cut))
library(cowplot)
plot_grid(a,b)

注:fill是将颜色映射到柱形图内部,而color是将颜色映射到轮廓。
- 通过position的参数变换,可以调整柱形图的位置。
ggplot(diamonds)+geom_bar(mapping=aes(x=cut,fill=clarity),position="fill")

ggplot(diamonds)+geom_bar(mapping=aes(x=cut,fill=clarity),position="identity")

ggplot(diamonds)+geom_bar(mapping=aes(x=cut,fill=clarity),position="dodge")

- 同理,我们发现,由于数据是处理好精确到个位的,画散点图时可能会出现不同的点堆叠到一起了,效果不是很好。于是加一个jitter随机扰动
ggplot(data=mpg)+geom_point(mapping=aes(x=displ,y=hwy),position="jitter)

六 坐标轴
coord_flip 将坐标轴横过来
ggplot(data=mpg,mapping=aes(x=class,y=hwy))+geom_boxplot()+coord_flip()

coord_polar 将条形图转化成饼图
ggplot(diamonds)+geom_bar(mapping=aes(x=cut,fill=cut),show.legend = F,width=1)+coord_polar()

六 分面
ggplot(data=mpg)+geom_point(mapping=aes(x=displ,y=hwy))+facet_wrap(~class,nrow=2)

按照某个横纵坐标分面
ggplot(data=mpg)+geom_point(mapping=aes(x=displ,y=hwy))+facet_grid(drv~cyl)
