查看原文
其他

R可视化——ggplot2包实现图形分面技巧汇总

王志山 科研后花园 2023-09-08

ggplot2包中实现图形分面主要通过facet_wrap()facet_grid()两个函数实现,但是两者之间还是存在一些差别。今天,小编通过示例给大家介绍一下如何在使用ggplot2包绘制图形时实现图形分面!

R包及数据加载

1、加载R包

#设置工作环境rm(list=ls())setwd("D:\\test")#加载包library(ggplot2)library(reshape2)library(ggprism)library(ggpubr)

2、加载数据,大家也可根据个人数据进行调整导入:

#加载数据df <- read.table("data.txt",header = T, check.names = F)#转换数据data=melt(df)data$G<-rep(c("T","F","H"), each = 24)


3、以柱状图形式展示数据

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函数实现图形分面

facet_wrap()函数可以通过~x、~x+b或者x~b的格式输入分面变量,且可以自由排版分面行方向的个数和列方向的个数:

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")pp+facet_wrap(~G)

p+facet_wrap(~G+variable)

p+facet_wrap(G~variable)

2、控制分面的行数和列数——主要通过ncol和nrow两个参数实现(可单独设置):

p+facet_wrap(~G,ncol = 2, nrow = 2)

3、子图坐标轴调整——通过scales参数控制,可选择fixed、free、free_x及free_y四个值


1)scales = "fixed"实现固定各子图坐标轴,即各子图坐标轴完全一样:

p+facet_wrap(~variable, scales = "fixed")

2)scales = "free"实现各子图坐标轴随其数值进行调整,即各子图坐标轴由其各自数值决定:

p+facet_wrap(~variable, scales = "free")

2)scales = "free_x"和scales = "free_y"分别实现各子图x或y坐标轴随其数值进行调整:

p+facet_wrap(~variable, scales = "free_x")#x轴随意变化p+facet_wrap(~variable, scales = "free_y")#y轴随意变化

4、子图标题颜色、背景、位置等设置

p+facet_wrap(~variable, scales = "free", strip.position = "right")+#子图标题位置 theme(strip.background = element_rect(fill = "grey",#子图标题背景色 linetype = "dotted"),#子图标题边框线 strip.text = element_text(color = "red",#子图标题字体颜色 face = "bold",#子图标题字体粗细 size = 10))#子图标题字体大小

5、去除子图标题背景:

p+facet_wrap(~variable, scales = "free")+ theme(strip.background = element_blank())

6、去除子图的标题

p+facet_wrap(~variable, scales = "free")+ theme(strip.text = element_blank())

通过fact_grid函数实现图形分面

facet_grid()函数主要通过y~.或.~x或y~x格式输入分面变量,但无法指定行数或列数,其他设置与facet_wrap()一致,可参考上文:
p+facet_grid(.~G)#横向排布

p+facet_grid(G~.)#纵向排布

p+facet_grid(group~G) #两个变量,前面的参数控制行分面,后面的参数控制列分面

参考:https://www.math.pku.edu.cn/teachers/lidf/docs/Rbook/html/_Rbook/ggplot2.html

我就知道你“在看”

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存