???? ggplot2包中實(shí)現(xiàn)圖形分面主要通過facet_wrap()和facet_grid()兩個(gè)函數(shù)實(shí)現(xiàn)爽彤,但是兩者之間還是存在一些差別杠袱。今天赡茸,小編通過示例給大家介紹一下如何在使用ggplot2包繪制圖形時(shí)實(shí)現(xiàn)圖形分面审葬!
R包及數(shù)據(jù)加載
1森缠、加載R包
#設(shè)置工作環(huán)境
rm(list=ls())
setwd("D:\\test")
#加載包
library(ggplot2)
library(reshape2)
library(ggprism)
library(ggpubr)
2拔鹰、加載數(shù)據(jù),大家也可根據(jù)個(gè)人數(shù)據(jù)進(jìn)行調(diào)整導(dǎo)入:
#加載數(shù)據(jù)
df <- read.table("data.txt",header = T, check.names = F)
#轉(zhuǎn)換數(shù)據(jù)
data=melt(df)
data$G<-rep(c("T","F","H"), each = 24)
3贵涵、以柱狀圖形式展示數(shù)據(jù)
ggplot(data,aes(G,value,color=G,fill=G))+
geom_bar(stat="summary",fun=mean,position="dodge")+
stat_summary(fun.data = 'mean_sd', geom = "errorbar", width = 0.3)+
labs(x="Samples",y=NULL)+
theme_prism(palette = "candy_bright",
base_fontface = "plain",
base_family = "serif",
base_size = 16,
base_line_size = 0.8,
axis_text_angle = 45)+
scale_fill_prism(palette = "candy_bright")
通過fact_wrap函數(shù)實(shí)現(xiàn)圖形分面
???? facet_wrap()函數(shù)可以通過x列肢、x+b或者x~b的格式輸入分面變量,且可以自由排版分面行方向的個(gè)數(shù)和列方向的個(gè)數(shù):
1宾茂、基本展示
p<-ggplot(data,aes(group,value,color=group,fill=group))+
geom_bar(stat="summary",fun=mean,position="dodge")+
labs(x=NULL,y=NULL)+
theme_classic()+
scale_fill_prism(palette = "floral")
p
p+facet_wrap(~G)
p+facet_wrap(~G+variable)
p+facet_wrap(G~variable)
2瓷马、控制分面的行數(shù)和列數(shù)——主要通過ncol和nrow兩個(gè)參數(shù)實(shí)現(xiàn)(可單獨(dú)設(shè)置):
p+facet_wrap(~G,ncol = 2, nrow = 2)
3、子圖坐標(biāo)軸調(diào)整——通過scales參數(shù)控制跨晴,可選擇fixed欧聘、free、free_x及free_y四個(gè)值:
1)scales = "fixed"實(shí)現(xiàn)固定各子圖坐標(biāo)軸端盆,即各子圖坐標(biāo)軸完全一樣:
p+facet_wrap(~variable, scales = "fixed")
2)scales = "free"實(shí)現(xiàn)各子圖坐標(biāo)軸隨其數(shù)值進(jìn)行調(diào)整怀骤,即各子圖坐標(biāo)軸由其各自數(shù)值決定:
p+facet_wrap(~variable, scales = "free")
3)scales = "free_x"和scales = "free_y"分別實(shí)現(xiàn)各子圖x或y坐標(biāo)軸隨其數(shù)值進(jìn)行調(diào)整:
p+facet_wrap(~variable, scales = "free_x")#x軸隨意變化
p+facet_wrap(~variable, scales = "free_y")#y軸隨意變化
4冤馏、子圖標(biāo)題顏色感挥、背景、位置等設(shè)置
p+facet_wrap(~variable, scales = "free",
strip.position = "right")+#子圖標(biāo)題位置
theme(strip.background = element_rect(fill = "grey",#子圖標(biāo)題背景色
linetype = "dotted"),#子圖標(biāo)題邊框線
strip.text = element_text(color = "red",#子圖標(biāo)題字體顏色
face = "bold",#子圖標(biāo)題字體粗細(xì)
size = 10))#子圖標(biāo)題字體大小
5圣蝎、去除子圖標(biāo)題背景:
p+facet_wrap(~variable, scales = "free")+
theme(strip.background = element_blank())
6焚鹊、去除子圖的標(biāo)題
p+facet_wrap(~variable, scales = "free")+
theme(strip.text = element_blank())
通過fact_grid函數(shù)實(shí)現(xiàn)圖形分面
???? facet_grid()函數(shù)主要通過y.或.x或y~x格式輸入分面變量凉敲,但無法指定行數(shù)或列數(shù),其他設(shè)置與facet_wrap()一致,可參考上文:
p+facet_grid(.~G)#橫向排布
p+facet_grid(G~.)#縱向排布
p+facet_grid(group~G) #兩個(gè)變量爷抓,前面的參數(shù)控制行分面势决,后面的參數(shù)控制列分面