ggplot2繪圖系統(tǒng)——圖形分面
ggplot2的分面faceting,主要有三個(gè)函數(shù):
- facet_grid
- facet_wrap
- facet_null (不分面)
1. facet_grid函數(shù)
facet_grid函數(shù)及參數(shù):
facet_grid(facets, #x~y, x+y~z
margins = F, #僅展示組合數(shù)據(jù)
scales = 'fixed', #是否通用坐標(biāo)軸瞳遍,free_x/free_y/free
space = 'fixed', #是否保持相同面積
shrink = T,
labeller = 'label_value', #添加標(biāo)簽
as.table = T,
switch = , #調(diào)整分面標(biāo)簽位置识藤,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
分面的靈活性丙挽。
分別定義不同圖形的坐標(biāo)軸取值范圍(scales參數(shù))或不同分面面積(space參數(shù))角骤。
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)) #設(shè)置y軸標(biāo)簽
image.png
分面標(biāo)簽設(shè)置
默認(rèn)標(biāo)簽使對應(yīng)分類水平的名稱,可通過設(shè)置labeller參數(shù)及對應(yīng)的函數(shù)對分面標(biāo)簽進(jìn)行修改迫靖。函數(shù)主要有:
- label_both (最常用):講變量名和分類水平一起展示蜒什;
- label_bquote(很適合填充數(shù)學(xué)表達(dá)式標(biāo)簽):接受rows和cols參數(shù)测秸,分別定義橫向和縱向分面標(biāo)簽;
- label_context:與label_both類似灾常;
- label_parse:與label_bquote類似霎冯。
p <- ggplot(mtcars,aes(wt,mpg))+geom_point()
p+facet_grid(vs~cyl,labeller = label_both)+ #設(shè)置分面標(biāo)簽
theme(strip.text = element_text(color='red'))
p+facet_grid(.~vs,labeller = label_bquote(cols = alpha ^ .(vs)))
#這里只設(shè)置cols,即必須存在列分面
image.png
image.png
改變標(biāo)簽的方向(默認(rèn)右钞瀑,上)沈撞,switch參數(shù)。
p+facet_grid(am~gear,switch='both')+ #右上變?yōu)樽笙? theme(strip.background = element_blank()) #去掉標(biāo)簽背景
image.png
多重分面:三個(gè)及以上變量同時(shí)分面雕什。
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不僅展示不同組合分面缠俺,還展示總體數(shù)據(jù)(all)分布的分面
mg+facet_grid(vs+am~gear,margins = 'am',labeller = label_both)
#am在切分不同水平和不切分時(shí)的數(shù)據(jù)分面
image.png
image.png
image.png
2. facet_wrap函數(shù)
與facet_grid的最大區(qū)別在于:能夠自定義分面行列數(shù)。
函數(shù)及其參數(shù):
facet_wrap(facets = ,
nrow = , #分面行數(shù)
ncol = , #分面列數(shù)
scales = 'fixed',
shrink = T,
labeller = 'label_value',
as.table = T,
switch = ,
drop = T,
dir = 'h') #h/v贷岸,按行/列排列分面