R语言与医学统计图形-【25】ggplot图形分面

ggplot2绘图系统——图形分面

ggplot2的分面faceting,主要有三个函数:

  • facet_grid
  • facet_wrap
  • facet_null (不分面)

1. facet_grid函数

facet_grid函数及参数:

facet_grid(facets, #x~y, x+y~z
           margins = F, #仅展示组合数据
           scales = 'fixed', #是否通用坐标轴,free_x/free_y/free
           space = 'fixed', #是否保持相同面积
           shrink = T,
           labeller = 'label_value', #添加标签
           as.table = T,
           switch = , #调整分面标签位置,both/x/y
           drop = T)

基本用法

p <- ggplot(mpg,aes(displ,cty))+geom_point()
a <- p+facet_grid(.~cyl) #cyl列
b <- p+facet_grid(drv~.) #drv行
c <- p+facet_grid(drv~cyl) #drv行cyl列
grid.arrange(a,b,c,ncol=1)

image.png
分面的灵活性。
分别定义不同图形的坐标轴取值范围(scales参数)或不同分面面积(space参数)。

mt <- ggplot(mtcars,aes(mpg,wt,color=factor(cyl)))+
  geom_point()
mt+facet_grid(.~cyl,scales = 'free')

image.png

ggplot(mpg,aes(drv,model))+geom_point()+
  facet_grid(manufacturer~.,scales = 'free',space = 'free')+
  theme(strip.text.y = element_text(angle=0)) #设置y轴标签

image.png

分面标签设置
默认标签使对应分类水平的名称,可通过设置labeller参数及对应的函数对分面标签进行修改。函数主要有:

  • label_both (最常用):讲变量名和分类水平一起展示;
  • label_bquote(很适合填充数学表达式标签):接受rows和cols参数,分别定义横向和纵向分面标签;
  • label_context:与label_both类似;
  • label_parse:与label_bquote类似。
p <- ggplot(mtcars,aes(wt,mpg))+geom_point()
p+facet_grid(vs~cyl,labeller = label_both)+ #设置分面标签
  theme(strip.text = element_text(color='red'))

p+facet_grid(.~vs,labeller = label_bquote(cols = alpha ^ .(vs)))
#这里只设置cols,即必须存在列分面

image.png

image.png
改变标签的方向(默认右,上),switch参数。

p+facet_grid(am~gear,switch='both')+ #右上变为左下
  theme(strip.background = element_blank()) #去掉标签背景

image.png
多重分面:三个及以上变量同时分面。

mg <- ggplot(mtcars,aes(x=mpg,y=wt))+geom_point()
mg+facet_grid(vs+am~gear,labeller = label_both)

mg+facet_grid(vs+am~gear,margins = T,labeller = label_both)
#margin不仅展示不同组合分面,还展示总体数据(all)分布的分面

mg+facet_grid(vs+am~gear,margins = 'am',labeller = label_both)
#am在切分不同水平和不切分时的数据分面

image.png
image.png
image.png

2. facet_wrap函数

与facet_grid的最大区别在于:能够自定义分面行列数。
函数及其参数:

facet_wrap(facets = ,
           nrow = , #分面行数
           ncol = , #分面列数
           scales = 'fixed',
           shrink = T,
           labeller = 'label_value',
           as.table = T,
           switch = ,
           drop = T,
           dir = 'h') #h/v,按行/列排列分面
原文地址:https://www.cnblogs.com/jessepeng/p/12307809.html