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,按行/列排列分面


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM