在公众号iMeta上看到的教程,跟着复制粘贴,试了之后发现导入文件的代码和随机生成矩阵的代码不管有没有都会生成图片,且如果不加set.seed()代码的话每次生成的图片都不相同,以下是代码:
library("igraph",warn.conflicts = FALSE)
library(igraph)
library("fastcluster",warn.conflicts = FALSE)
library("WGCNA",warn.conflicts = FALSE)
library(WGCNA)
#set.seed(1)
#otu<-data.frame(replicate(6,sample.int(10,1000,replace = T)))
#rownames(otu)<-paste0('ASV_',1:nrow(otu))
#colnames(otu)<-c('A1','A2','A3','B1','B2','B3')
#dim(otu)
write.table(otu,file="abc.txt",sep="\t",quote=F,row.names=T,col.names= T)
otu=read.table(("abc.txt"),header=T,row.names=1,sep="\t",comment.char="")
CorrDF <- function(cormat, pmat) {
ut <- upper.tri(cormat)
data.frame(
from = rownames(cormat)[col(cormat)[ut]],
to = rownames(cormat)[row(cormat)[ut]],
cor = (cormat)[ut],
p = pmat[ut]
)
}
occor <- corAndPvalue(t(otu), use='pairwise', method='spearman')
cor_df <- CorrDF(occor$cor , occor$p)
cor_df <- cor_df[which(abs(cor_df$cor) >= 0.6),]
cor_df <- cor_df[which(cor_df$p < 0.001),]
igraph <- graph_from_data_frame(cor_df, direct=F)
length(V(igraph))
length(E(igraph))
V(igraph)$size <- degree(igraph)*0.8
cols <- c('#00A6FB', '#0582CA', '#fff0f3', '#006494', '#c9e4ca', '#31572c', '#90a955', '#ecf39e', '#a4133c', '#c9184a', '#ff4d6d')
V(igraph)$color <- sample(cols, length(V(igraph)), replace = T)
E(igraph)$color[E(igraph)$cor >= 0.6] <- "darkgray"
E(igraph)$color[E(igraph)$cor <= -0.6] <- "red"
E(igraph)$width <- abs(E(igraph)$cor)*0.5
coords <- layout_with_fr(igraph, niter=9999,grid="nogrid")
pdf("Figure1C4.pdf", height = 10,width = 10)
plot(igraph, layout=coords, vertex.label = NA, vertex.frame.color=NA)
dev.off()
什么叫不管有没有都会生成图片,其次这部分涉及随机性,不设置随机种子那当然会每次结果都不一样
occor <- corAndPvalue(t(otu), use='pairwise', method='spearman'):这行代码计算相关系数和显著性水平。由于在计算中使用了pairwise和spearman方法,不同的数据或不同的计算方法可能会导致每次运行得到不同的相关系数结果。
V(igraph)$color <- sample(cols, length(V(igraph)), replace = T):这行代码使用sample()函数随机选择节点颜色,并将其赋值给igraph图中的节点。由于使用了随机抽样,每次运行时颜色分配可能会不同。
coords <- layout_with_fr(igraph, niter=9999,grid="nogrid"):这行代码使用Fruchterman-Reingold算法为节点生成布局坐标。由于算法的随机性和迭代次数(niter),每次运行时生成的节点布局可能会有所不同。