R可视化——ggplot2绘制柱状堆积图并添加连线
2022-08-10 本文已影响0人
科研那点事儿
安装、加载R包
#clear Global Environment
rm(list=ls())
#安装包
# install.packages("ggplot2")
# install.packages("ggprism")
# install.packages("reshape")
# install.packages("ggalluvial")
#加载包
library(ggplot2)
library(ggprism)
library(reshape)
library(ggalluvial)
构造数据并对其进行处理
#构造数据
df<-data.frame(samples=c('a','b','c','d','e'),
A=c(0.3,0.25,0.1,0.2,0.15),
B=c(0.6,0.1,0.05,0.2,0.05),
C=c(0.4,0.2,0.1,0.15,0.15),
D=c(0.1,0.2,0.3,0.3,0.1))
#变量格式转换,宽数据转化为长数据,方便后续作图
df1 <- melt(df,id.vars = 'samples',measure.vars = c('A','B','C','D'))
names(df1)[1:2] <- c("group","X") #修改列名
image.png
绘图
1、绘制柱状堆积图
ggplot(df1, aes( x = X,y=100 * value,fill = group))+
geom_col(position = 'stack', width = 0.6)
image.png
2、使用ggplot2拓展包ggalluvial重新绘制并添加连线
ggplot(df1, aes( x = X,y=100 * value,fill = group,
stratum = group, alluvium = group))+
geom_stratum(width = 0.5, color='white')+
geom_alluvium(alpha = 0.5,
width = 0.5,
curve_type = "linear")
image.png
模板代码
ggplot(df1, aes( x = X,y=100 * value,fill = group,
stratum = group, alluvium = group))+
geom_stratum(width = 0.7, color='white')+
geom_alluvium(alpha = 0.5,
width = 0.7,
color='white',
size = 1,
curve_type = "linear")+
scale_y_continuous(expand = c(0,0))+
labs(x="Samples",y="Relative Abundance(%)",
fill="group")+
guides(fill=guide_legend(keywidth = 1, keyheight = 1)) +
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 = 'top')
image.png