ggplot第三篇-小图会分身
2018-08-20 本文已影响34人
小洁忘了怎么分身
注意这里的分面指的是同一类型的图(比如都是点图,都是折线图)分好几个小图,而不是不同类型的图拼在一起:
1.示例数据
在公众号回复:dexp.csv,获得示例数据。
读取数据:
dexp <- read.csv("dexp.csv",row.names = 1)#设置第一列为行名
示例数据:40个基因,每个基因9个重复,加上这9个重复各自的观测值,以及每个基因的长度。
2.分面的函数
(1)facet_wrap
重要参数:
facets: 分面参数如 ~Group,表示用 Group 变量进行数据分类
nrow: 绘制图形的行数
ncol: 绘制图形的列数,nrow/ncol只设定一个即可
scales: fixed,小图均使用统一坐标;
free每个小图按照各自数据范围自由调整坐标;
free_x为自由调整x轴刻度范围;
free_y为自由调整y轴刻度范围。
(2)facet_grid
与facet_wrap不同的重要参数:
facets: 应用两个标准分面,如Gene ~ Group
margins: Ture,包含所有数据的组
space: 每张小图的幅宽,可设置为固定(fixed)和自由(free,free_x,free_y)
3.简单举例-按照Group分面,就是分三面
按照Group分面的点图

把多余的坐标删掉,用scales
ps<-ggplot(data = dexp, aes(x = Sample, y = Expression))
ps + geom_point(aes(color=Gene)) +
facet_wrap(~Group,scales = "free_x")

按照Group分面的折线图
ps<-ggplot(data = dexp, aes(x = Sample, y = Expression))
ps + geom_line(aes(group=Gene,color=Gene)) +
facet_wrap(~Group, scales = "free_x")

2.按照Sample分面,就是分9面
pg<-ggplot(data = dexp, aes(x = Gene, y = Expression,color=Sample))
pg + geom_point() +
facet_wrap(~Sample, scales = "free_x", nrow = 3)

3.按照Gene分面,就是分40面
pg<-ggplot(data = dexp, aes(x = Gene, y = Expression,color=Sample))
pg + geom_point() +
facet_wrap(~Sample, scales = "free_x", nrow = 3)

折线图颜值更高
ps<-ggplot(data = dexp, aes(x = Sample, y = Expression))
ps + geom_line(aes(group=Gene,color=Gene)) +
facet_wrap(~Gene, scales = "free_x", nrow = 5) #也可以ncol=8

4.根据两个变量来分面-- facet_grid
(1)从一张怂图认识 facet_grid
如果要展示4个基因、9个样品的表达量,将9个样品分为三组,每组一图。
dexp_small<-filter(dexp, Gene %in% paste("G", 1:4, sep = ""))
psm<-ggplot(data = dexp_small, aes(x = Sample, y = Expression))
psm + geom_point() +
facet_grid(Gene ~ Group) #按照基因分行,Group分列

(2)调整坐标和颜色
坐标调整的参数是scales,
fixed,小图均使用统一坐标;
free每个小图按照各自数据范围自由调整坐标;
free_x为自由调整x轴刻度范围;
free_y为自由调整y轴刻度范围。
dexp_small<-filter(dexp, Gene %in% paste("G", 1:4, sep = ""))
psm<-ggplot(data = dexp_small, aes(x = Sample, y = Expression))
psm + geom_point(aes(color=Length)) +
facet_grid(Gene ~ Group, scales = "free_x")

(3)添加一个包含所有数据的组(汇总),并使每幅图的幅宽自由调整
dexp_small<-filter(dexp, Gene %in% paste("G", 1:4, sep = ""))
psm<-ggplot(data = dexp_small, aes(x = Sample, y = Expression))
psm + geom_point(aes(color=Length)) +
facet_grid(Gene ~ Group, scales = "free_x", margins = T,space = "free")
