分享

使用相关矩阵构造多个格式的网络文件(igraph,Gephi,ggraph)

 微生信生物 2021-01-16

写在前面

outputgephi函数:可以使用相关矩阵和微生物群落的phyloseq对象直接生成Gephi软件需要两个文件,直接保存即可。

nodeEdge函数:可以生成边文件和节点文件,用于制作ggraph对象或者igraph对象。

输入文件

#--导入所需R包#-------
library(igraph)
library(network)
library(sna)
library(ggClusterNet)
library(tidyverse)

ps = readRDS("../ori_data/ps_liu.rds")
ps

corMicro函数用于计算相关

按照丰度过滤微生物表格,并却计算相关矩阵,按照指定的阈值挑选矩阵中展示的数值。

#----------计算相关#----
result = corMicro (ps = ps,N = 0.02,r.threshold=0.6,p.threshold=0.05,method = "pearson")
#--提取相关矩阵
cor = result[[1]]
dim(cor)

构造Gephi的输入网络文件

gephi <- outputgephi(ps = result[[3]],cor = cor)
edge_Gephi <- gephi[[1]]
head(edge_Gephi)
node_Gephi <- gephi[[2]]
head(node_Gephi)

nodeEdge函数生成节点和边文件

nodeEdge:用于将相关矩阵转化为边文件和节点文件。默认zero = TRUE,将不相关的点去除。

result4 = nodeEdge(cor = cor)

#提取变文件
edge = result4[[1]]
dim(edge)
#--提取节点文件
node = result4[[2]]
dim(node)

构造igraph对象

#-------输出igraph对象
#--这里将为0的也添加进去了,但是这些边其实都是离散的。
igraph = igraph::graph_from_data_frame(edge, directed = FALSE, vertices = node)
#--------------------igraph对象
# ## 边的权重
# E(igraph)$weight
# #边的显著性标签
# E(igraph)$p
# # 节点属性
# V(igraph)$name
#---------如何设置igraph的出图相关可视化设置

#------边----------------------设置边的颜色-一般而言我们按照正负相关分别上两种颜色
E.color <- E(igraph)$weight
E.color <- ifelse(E.color>0, "red",ifelse(E.color<0, "blue","grey"))
E(igraph)$color <- as.character(E.color)
# 边的粗细----------??
# E(igraph)$width = abs(E(igraph)$weight)

#-----------可视化---------设置layout
l <- layout_nicely(igraph)
l <- norm_coords(l, ymin=-1, ymax=1, xmin=-1, xmax=1)
#--------------------出图
plot(igraph,main=paste( "network",sep = ""),
layout=l,
# vertex.shape="fcircle",
# vertex.frame.color="white",
vertex.label=NA ,
vertex.frame.color="#984EA3",
vertex.color="#984EA3",
vertex.size =2,
vertex.frame.alpha =0.5,
edge.width=0.5,
edge.lty=2,
edge.curved=F,
margin=c(0,0,0,0)
#vertex.frame.width=5
)

构造到 ggraph 对象

library(tidygraph)
library(ggraph)

tbl_graph = tidygraph::tbl_graph(nodes = node, edges = edge, directed = FALSE)
tbl_graph
ggraph(tbl_graph , layout = 'linear', circular = TRUE) +
# geom_edge_arc() +
# geom_edge_fan() +
geom_edge_link(aes(edge_colour = direction))+
geom_node_point() # 对网络的点进行设置

当我们想把离散的点也展现

设置zero = FALSE即可表示离散

result4 = nodeEdge(cor = cor,zero = FALSE)
#提取变文件
edge = result4[[1]]

#--提取节点文件
node = result4[[2]]
dim(node)

tbl_graph = tidygraph::tbl_graph(nodes = node, edges = edge, directed = FALSE)
tbl_graph
ggraph(tbl_graph , layout = 'linear', circular = TRUE) +
# geom_edge_arc() +
# geom_edge_fan() +
geom_edge_link(aes(edge_colour = direction))+
geom_node_point() # 对网络的点进行设置

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多