ggplot实现分页画图
2020-01-21 本文已影响0人
生信编程日常
一般分页绘图可以用par(nfrow()),但是这一方法在ggplot2中并不适用,ggplot2使用facet把数据按分类进行画图。
对一个变量进行分类
要想通过单个变量对图进行分面,可以使用函数 facet_wrap()。其第一个参数是一个公 式,创建公式的方式是在 ~ 符号后面加一个变量名
library(ggplot2)
data(iris)
head(iris)

p <-ggplot(iris,aes(x=Sepal.Length,y= Sepal.Width)) +geom_point()
p

p <-ggplot(iris,aes(x=Sepal.Length,y= Sepal.Width)) +geom_point()+facet_wrap(~ Species)
p

可以设置行列个数:如按照Petal.Width设置成三行
ggplot(iris,aes(x=Sepal.Length,y= Sepal.Width)) +geom_point()+ facet_wrap( .~ Petal.Width,nrow = 3)

对二个变量进行分类
要想通过两个变量对图进行分面,需要在绘图命令中加入函数 facet_grid()。这个函数的 第一个参数也是一个公式,但该公式包含由 ~ 隔开的两个变量名。
gplot(iris,aes(x=Sepal.Length,y= Sepal.Width)) +geom_point()+facet_grid(Species ~ Petal.Width)

欢迎关注微信公众号:生信编程日常
