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

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")
p
p+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

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章