# 清空当前环境中的所有对象
rm (list = ls ())
setwd("C:\\Users\\Administrator\\Desktop\\新建文件夹\\Stacked bar chart") #设置工作目录
library(ggplot2) # 用于绘图
library(ggalluvial) # 用于绘制柱状图背后的条带
library(grid) # 用于访问unit函数
ra <- as.matrix(read.table("Phylum_top10.txt", row.names =1,
header = F, sep = "\t")) # 读入相对丰度数据并转换为矩阵方便后续数据整理
group <- c("B73", "Mo17") # 品种变量
code <- c("B_DAS28","B_DAS42","B_DAS56","B_DAS70","M_DAS28","M_DAS42","M_DAS56","M_DAS70") # 8组处理变量
code_rep <- rep(code, each = 11)
taxa_rep <- rep(rownames(ra), 8)
cultivar_rep <- rep(group, each = 44)
abundance_vec <- as.vector(ra)
dat <- data.frame(code = code_rep,
Phylum = taxa_rep,
cultivar = cultivar_rep,
abundance = abundance_vec)
dat$Phylum <- factor(dat$Phylum, levels = c("Proteobacteria","Actinobacteria","Bacteroidetes","Firmicutes",
"Planctomycetes","Acidobacteria","Verrucomicrobia","Gemmatimonadetes","Deinococcus-Thermus",
"Cyanobacteria","Others"))
ggplot(dat, aes(x = code, y = abundance, fill = Phylum))+
geom_bar(stat = "identity", width = 0.6, alpha = 1)+ # 柱状图绘制
geom_flow(aes(alluvium = Phylum), alpha = 0.4) + # 添加柱状图后的条带
scale_fill_manual(values = c(
"#76B4BD", # 类似于B73但稍微深一点
"#E9C46A", # 类似于Mo17但稍微亮一点
"#88C695", # 类似于DAS28但更偏向绿色
"#F4E3A1", # 类似于DAS42但更亮
"#C9A8C5", # 类似于DAS56但更淡
"#6D6DB5", # 类似于DAS70但更亮
"#5BA8A0", # 新增颜色,提供与上述颜色不同的选项
"#F2A2C7", # 新增颜色,鲜艳且易于区分
"#9CAD60", # 新增颜色,自然而柔和
"#BC8F8F", # 新增颜色,温暖的中性色
"#C0C0C0" # 新增颜色,为“Other”分类提供一个中性选项
))+
theme_bw()+ # 将主题调整为白色背景和浅灰色网格线
facet_grid(.~cultivar, scales = "free_x", space = "free_x")+ # 按照cultivar这个变量进行分块
xlab("")+ # 去掉x轴的标题
ylab("Relative abundance (%)")+ # 设置y轴的标签
theme(panel.grid.major.x = element_blank(),
axis.text.x = element_text(size = rel(1.2), angle = 0, face = "plain", color = "black"),
axis.text.y = element_text(size=rel(1.2), face = "plain", color = "black"),
legend.text = element_text(size = rel(1)),
strip.text.x = element_text(size = rel(1.5), face = "bold"),
strip.background = element_rect(fill = "lightblue", size = 1),
panel.border = element_rect(colour = "black", fill = NA, size = 1.2),
axis.title.y = element_text(size = 14),
legend.position = "bottom",
legend.title = element_blank(),
legend.key.size = unit(0.5, "cm"), # 控制图例项的大小
legend.spacing.x = unit(0.1, "cm"), # 控制图例项之间的水平间距
legend.box.margin = margin(t = -20, unit = "pt")) + # 自定义图例与横坐标的距离
guides(fill = guide_legend(ncol = 6)) + # 根据需要调整图例项的列数
scale_y_continuous(expand = c(0, 0.01))
ggsave("Abundance2.png", width = 10, height = 7) # 图片导出,导出为pdf文件,设置图片长和宽
标签:library,Desktop,堆叠,柱状图,用于,丰度 From: https://www.cnblogs.com/wzbzk/p/18060283