16S与代谢相关性网络图绘制

最近画了网络图,赶紧来记录一下,怕忘记了!下次还用的着

1. 出图结果:

2. 代码:

library(ggplot2)
library(readxl)
library(stringr)
library(ggraph)
library(igraph)
library(reshape2)
library(showtext)
showtext_auto()  ## 用来解决保存PDF图片字体报错问题
theme_set(theme_bw()) 
## 代谢丰度(行为代谢名称,列为样本名字)
meta <- read.table("meta.txt", header = T, row.names = 1, sep="\t")

## 物种丰度(行为物种,列为样本名字)
amp <- read.table("tax.txt",  header = T, row.names = 1, sep="\t")

## 计算相关性
x <- cor(t(amp), t(meta), method="spearman")

cor.m <- melt(x, factorsAsStrings=T)
colnames(cor.m) <- c("Taxon", "Metabolite", "cor")
cor.m$Taxon <- as.character(cor.m$Taxon)
cor.m$Metabolite <- as.character(cor.m$Metabolite)
cor.m$correlation <- "positive"
cor.m$correlation[which(cor.m$cor < 0)] <- "negative"
cor.m$correlation <- factor(cor.m$correlation, levels=c("negative", "positive"))
cor.m$cor <- abs(cor.m$cor)
taxon <- unique(cor.m$Taxon)
meta <- unique(cor.m$Metabolite)
node_attr <- data.frame(node=c(taxon, meta), attr=c(rep("Taxon", length(taxon)), rep("Metabolite", length(meta))))
  node_attr$name <- node_attr$node
  net <- igraph::graph_from_data_frame(d=cor.m, directed=F, vertices=node_attr)
  igraph::V(net)$degree <- igraph::degree(net)
  igraph::V(net)$size <- igraph::degree(net)/5
  igraph::E(net)$width <- igraph::E(net)$cor

p <- ggraph(net, layout="linear", circular=T) + 
    geom_edge_arc(aes(edge_width=width, color=correlation), show.legend=T) + 
    geom_node_point(aes(size=size, color=attr), alpha=0.8, show.legend=T) + 
    geom_node_text(aes(filter=degree>1, label=name), size=3, repel=F) + 
    scale_edge_width(range=c(0.4, 1)) + scale_size_continuous(range=c(3, 8)) + 
    scale_colour_manual(values=c("#EFA3AC", "#2ABEBA"), breaks=c("Taxon", "Metabolite")) + 
    guides(size="none", edge_width="none") + labs(color="") + 
    theme_graph(foreground = "white", fg_text_colour = NA, base_family = "Arial Narrow") + 
    scale_edge_color_manual(values=c("#CCCC99", "#CCCCFF"), breaks=c("positive", "negative"))

png(filename = "network.png", width = 2800, height = 1800, res=200)  
print(p)
dev.off()

pdf(file = "network.pdf", width = 14, height = 12)
print(p)
dev.off()

 3. 遇到问题:

Error in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y,  :
  invalid font type

错误于grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, : 
  字体类别出错

首先确保你的电脑中有相应的字体,比如新罗马字体

其次在R中运行如下代码即可

library(showtext)
showtext_auto()  ## 用来解决保存PDF图片字体报错问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值