其他
R可视化——R语言中的多子图拼接指南
绘制子图
1、加载绘图包
#加载绘图包
library(ggplot2)
library(ggprism)
library(reshape)
library(ggpubr)
2、加载并处理数据
#数据
df <- data.frame(A = c(1, 2, 3, 4, 5, 6, 8, 12, 13),
B = c(1, 2, 4, 5, 7, 10,5,6,8),
C = c(1, 5, 6, 7, 8, 9, 10, 11, 13),
D = c(1, 2, 5, 8, 10, 13,5,8,6))
df1=melt(df)
colnames(df1)=c("group","value")
3、绘制子图
# fig.1
p1<-ggplot(df1,aes(x=group,y=value))+
stat_boxplot(geom = "errorbar", width=0.1)+
geom_boxplot(aes(fill=group),
outlier.colour="white")+
geom_jitter(width = 0.2)+
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")+
theme(legend.position="none")
p1
# fig.2
p2<-ggplot( df1, aes(x = group, y=value,color=group,fill=group) ) +
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")+
theme(legend.position="none")
p2
# fig.3
p3<-ggplot(df1, aes(x = group, y=value,fill=group))+
geom_violin(trim = T,position = position_dodge(width = 0.1))+
geom_boxplot(alpha=1,outlier.size=0, size=0.3, width=0.2,fill="white")+
stat_summary(fun="mean",geom="point",shape=21, size=2,fill="blue")+
labs(x="Samples",y=NULL)+
theme_prism(palette = "flames",
base_fontface = "plain",
base_family = "serif",
base_size = 16,
base_line_size = 0.8,
axis_text_angle = 45)+
scale_fill_prism(palette = "candy_bright")+
theme(legend.position = 'none')
p3
# fig.4
p4<-ggplot(df) +
geom_segment(aes(x=A, xend=A, y=0, yend=B), color="grey",size=1) +
geom_point( aes(x=A, y=B,color=A), size=4 ) +
theme_prism(palette = "pearl",
base_fontface = "plain",
base_family = "serif",
base_size = 14,
base_line_size = 0.8,
axis_text_angle = 45) +
theme(legend.position = "none") +
ggtitle("Lollipop Chart")
p4
cowplot包实现多子图拼接
cowplot::plot_grid(p1,p2,p3,p4,ncol = 2)#按照两行排列
cowplot::plot_grid(p1,p2,p3,p4,ncol = 1)#一列排列
cowplot::plot_grid(p1,p2,p3,p4,ncol = 4)#横向排列
gridExtra包实现多子图拼接
# 图形在这里就不做展示了,与cowplot包拼接一样
gridExtra::grid.arrange(p1,p2,p3,p4,
layout_matrix=rbind(c(1,2),c(3,4)))#将图形分割为4个区域,上面两个放置图1与图2,下面两个区域则放置图3与图4
gridExtra::grid.arrange(p1,p2,p3,p4,
layout_matrix=rbind(c(1,2,3,4)))#横向排列
gridExtra::grid.arrange(p1,p2,p3,p4,
layout_matrix=rbind(c(1),c(2),c(3),c(4)))#纵向排列
patchwork包实现自定义布局拼图
p1/p2#上下拼图
p1+p2#左右拼图
(p1+p2)/p3#混合拼图
p1+p2+p3/p4#混合拼图(不用括号则优先上下拼图再进行左右拼图)
p1+p2+p3+p4+
patchwork::plot_layout(design = "
AB
CD
")#分成四份,按照正方形布局排列
p1+p2+p3+p4+
patchwork::plot_layout(design = "
ABCD
")#分成四份,横向排列
p1+p2+p3+p4+
patchwork::plot_layout(design = "
A
B
C
D
")#分成四份,纵向排列
p1+p2+p3+p4+
patchwork::plot_layout(design = "
AABBBB#
AA###D#
##CC###
##CC###
")#自定义布局
爱我请给我好看!