引言
上一期内容我们介绍了基于R语言使用热图(Heatmap)对微生物丰度进行展示,今天这期内容主要介绍如何使用弦图(Chord Diagram)来展示物种丰度的计算结果!
正文——代码
1、工作目录设置及R包的加载
rm(list=ls())
setwd("D:\\桌面\\SCI论文写作与绘图物种丰度计算及可视化")
#安装、加载包
install.packages("circlize")
install.packages("statnet")
library(circlize)
library(statnet)
2、加载数据并对其进行处理
#准备数据(此前计算丰度生成的数据)
data <- read.table("Genus_x.txt",sep="\t",header = T,row.names = 1,check.names = F)
data <- as.matrix(m)#转换数据格式
#生成作图数据
df <- data.frame(from = rep(rownames(data), ncol(data)),
to = rep(colnames(data), each = nrow(data)),
value = as.vector(data))
3、绘图
1) 颜色设定
color=NULL
color[c("A","B","C","D","E")]=c("blue","red","yellow","green","pink")
color[rownames(data)]=c("#40A4D8","#33BEB7","#B2C224","#FECC2F","#FBA127",
"#F66320","#DB3937","#A463D7","#0C5BCE","grey","black")
2) 绘图
chordDiagram(df,
grid.col =color,#颜色
annotationTrack = "grid",
transparency = 0.2,#透明度
link.lwd = 0.00001,#线条宽度
link.lty = 1, # 线路类型
link.border = 0,#边框颜色
directional = -1,#表示线条的方向,0代表没有方向,1代表正向,-1代表反向,2代表双向
diffHeight = mm_h(3),#外圈和中间连线的间隔
direction.type = c("diffHeight","arrows"), #线条是否带有箭头
link.arr.type = "big.arrow",#箭头类型
annotationTrackHeight = c(0.04, 0.1))#网格高度
3) 添加标签并设置标签方向
circos.track(track.index = 1, panel.fun = function(x, y) {
circos.text(CELL_META$xcenter, CELL_META$ylim[1], CELL_META$sector.index,
facing = "clockwise", niceFacing = T, adj = c(-0.5, 0.5), cex = 0.8)
circos.axis(h = "top", labels.cex = 0.4,labels.niceFacing = F, labels.pos.adjust =F)
}, bg.border = NA)
4)生成图例
legend("right",pch=20,legend=rownames(data),
col=color[rownames(data)],bty="n",
cex=1,pt.cex=3,border="black")
由于绘图板大小限制,所以此时我们看到生成的图例与标签排版混乱,互相重叠,此时需要我们将其保存成PDF以将图例和图形主体部分分开。
4、保存
pdf(file="1.pdf", width=9, height=5, pointsize=8)
chordDiagram(df,
grid.col =color,
annotationTrack = "grid",#diy添加label和axis
transparency = 0.2,#透明度
link.lwd = 0.00001,#线条宽度
link.lty = 1, # 线路类型
link.border = 0,#边框颜色
directional = -1,#表示线条的方向,0代表没有方向,1代表正向,-1代表反向,2代表双向
diffHeight = mm_h(3),#外圈和中间连线的间隔
direction.type = c("diffHeight","arrows"), #线条是否带有箭头
link.arr.type = "big.arrow",#箭头类型
annotationTrackHeight = c(0.04, 0.1))#网格高度
circos.track(track.index = 1, panel.fun = function(x, y) {
circos.text(CELL_META$xcenter, CELL_META$ylim[1], CELL_META$sector.index,
facing = "clockwise", niceFacing = T, adj = c(-0.5, 0.5), cex = 0.8)
circos.axis(h = "top", labels.cex = 0.4,labels.niceFacing = F, labels.pos.adjust =F)
}, bg.border = NA)
legend("right",pch=20,legend=rownames(data),
col=color[rownames(data)],bty="n",
cex=1,pt.cex=3,border="black") # 设定图例
dev.off()
此时图例已经和图形主体部分分开,但是图中标签还是比较混乱,需要我们使用进行美化。
5、AI美化
源码及数据在公众号后台回复获取!!!