一、基本概念
在數據分析中,經常需要將數據按不同的變數分組,進行可視化展示。facet_wrap函數可以將一個變數按另一個變數分為多個小圖展示,非常方便的進行分組展示。
facet_wrap函數可以將一個變數拆分為多個子圖,設定參數nrow或ncol可以控制子圖的列數或行數,從而實現多條件分組展示。
ggplot(data, aes(x, y)) + geom_point() + facet_wrap(~group, ncol=3, nrow=2)
二、基本用法
facet_wrap最基本的用法,就是按某個變數分組展示數據。在下面的例子中,我們對iris數據集進行了分組展示,根據花萼長度(Sepal.Length)將花型按照3列展示,每列展示2個子圖。
ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + facet_wrap(~Species, ncol=3, nrow=2)
三、修改標題和展示方式
facet_wrap可以根據自己的需要修改子圖的標題和展示方式。通過在參數中添加主題(theme)、標籤(labeller)、展示方式(strip)等,可以完全自定義子圖的展示風格。
ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + facet_wrap(~Species, ncol=3, nrow=2, labeller = labeller(Species = c("setosa" = "山鳶尾", "versicolor" = "雜色鳶尾", "virginica" = "維吉尼亞鳶尾")), strip.position = "right", strip.background = element_blank(), strip.text = element_text(face="bold"), theme(strip.text = element_text(size=14, face="bold")))
四、修改排列方式
facet_wrap並不只是可以按照傳統的水平或垂直排列方式,還可以通過修改排列方式,實現更多樣化的展示風格。在下面的例子中,我們將iris數據集按照花型進行分組展示,但是展示方式並不是按照傳統的格子形排列,而是使用了蜂窩形排列方式。
ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + facet_wrap(~Species, ncol=2, nrow=2, switch = "both", labeller = labeller(Species = c("setosa" = "山鳶尾", "versicolor" = "雜色鳶尾", "virginica" = "維吉尼亞鳶尾")), strip.position = "bottom", strip.background = element_blank(), strip.text = element_text(face="bold"), theme(strip.text = element_text(size=14, face="bold")), scale_x_continuous(expand=c(0.2,0.2)))
五、調整子圖的尺寸
facet_wrap函數會自動調整子圖的尺寸,讓它們儘可能地填補整個繪圖區域。但是如果需要調整子圖的大小,也可以使用參數as.table = TRUE或者asp = ratio來實現。
ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + facet_wrap(~Species, ncol=3, nrow=2, as.table = T, labeller = labeller(Species = c("setosa" = "山鳶尾", "versicolor" = "雜色鳶尾", "virginica" = "維吉尼亞鳶尾")), strip.position = "bottom", strip.background = element_blank(), strip.text = element_text(face="bold"), theme(strip.text = element_text(size=14, face="bold")), scale_x_continuous(expand=c(0.2,0.2)))
六、改變子圖內容
facet_wrap不僅可以根據某個變數的不同值進行分組展示,還可以通過細緻地操作,實現更加複雜的展示方式。比如在下面的例子中,我們將iris數據集中的每類花分為3組,然後根據組別展示子圖,實現了更加細緻的展示效果。
iris$group <- cut(1:nrow(iris), breaks = 3, labels = c("小", "中", "大")) ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + facet_wrap(~group + Species, ncol=3, nrow=2, labeller = labeller(Species = c("setosa" = "山鳶尾", "versicolor" = "雜色鳶尾", "virginica" = "維吉尼亞鳶尾")), strip.position = "bottom", strip.background = element_blank(), strip.text = element_text(face="bold"), theme(strip.text = element_text(size=14, face="bold")), scale_x_continuous(expand=c(0.2,0.2)))
七、小結
facet_wrap作為一個非常重要的函數,常常用於分組展示數據。通過本文的介紹,讀者可以掌握facet_wrap函數的基本使用方式,以及如何根據自己的需要進行修改。掌握facet_wrap之後,讀者可以更加便捷的進行數據可視化處理。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/245491.html