背景:网络图是由点和边构成的图结构,常用来可视化基因调控网络等。本地图形化界面的网络图软件有Gephi和Cytoscape,这里使用R中的包绘制网络图,以便可视化加入到流程中。
- 数据预处理
可视化的网络图通常需要两个文件,边edges文件和点nodes文件,其中边文件通常包含(源节点,目标节点,边权重)的信息,点文件则包括所有的节点的唯一值即可。
#'数据预处理,构建edges和nodes表格
p_load("navdata","tidyverse", "igraph", "tidygraph", "ggraph")
data("phone.call")
head(phone.call, 3)
sources <- phone.call %>% distinct(source) %>% rename(label = source)
destinations <- phone.call %>% distinct(destination) %>% rename(label = destination)
nodes <- full_join(sources, destinations, by = "label")
nodes <- nodes %>% mutate(id = 1:nrow(nodes)) %>% select(id, everything()) #' 添加id
head(nodes)
phone.call <- phone.call %>% rename(weight = n.call) #' 列重命名
edges <- phone.call %>% left_join(nodes, by = c("source" = "label")) %>% rename(from = id) #'构建边列表
edges <- edges %>% left_join(nodes, by = c("destination" = "label")) %>% rename(to = id)
edges <- select(edges, from, to, weight)
head(edges)
- 方法一 使用igraph
#'方法一 使用igraph
library(igraph)
net.igraph <- graph_from_data_frame(d = edges, vertices = nodes,directed = TRUE)
set.seed(123)
png("fig1_my_test.png")
plot(net.igraph, edge.arrow.size = 0.2,layout = layout_with_graphopt)
dev.off()
结果like this:
igraph.png
- 方法二 使用tidygraph和ggraph
library(tidygraph)
library(ggraph)
net.tidy <- tbl_graph(nodes = nodes, edges = edges, directed = TRUE)
pp<-ggraph(net.tidy, layout = "graphopt") +
geom_node_point(col = 'gold',size = 2) + #'点信息
geom_edge_link(aes(width = weight), alpha = 0.8) + #'边信息
scale_edge_width(range = c(0.2, 2)) + #'控制粗细
geom_node_text(aes(label = label), repel = TRUE) + #'增加节点的标签,reple避免节点重叠
labs(edge_width = "phone.call") + #'图例标签
theme_graph()
ggsave("fig2_test.png",pp)
结果like this:
ggraph.png
如果想画成圆形:
pp<-ggraph(net.tidy, layout = "linear",circular=TRUE) +
geom_node_point(col = 'gold',size = 2) + #'点信息
geom_edge_link(aes(width = weight), alpha = 0.8) + #'边信息
scale_edge_width(range = c(0.2, 2)) + #'控制粗细
geom_node_text(aes(label = label), repel = TRUE) + #'增加节点的标签,reple避免节点重叠
labs(edge_width = "phone.call") + #'图例标签
theme_graph()
ggsave("fig3_test.png",pp)
ggraph.png
ggraph
的参数可以仔细调整,有很多叠加的图层。
总结:根据自己的习惯,封装成函数很好用。
网友评论