背景:網(wǎng)絡圖是由點和邊構成的圖結構更振,常用來可視化基因調控網(wǎng)絡等酥筝。本地圖形化界面的網(wǎng)絡圖軟件有Gephi和Cytoscape,這里使用R中的包繪制網(wǎng)絡圖,以便可視化加入到流程中。
- 數(shù)據(jù)預處理
可視化的網(wǎng)絡圖通常需要兩個文件碑韵,邊edges文件和點nodes文件,其中邊文件通常包含(源節(jié)點,目標節(jié)點窝稿,邊權重)的信息,點文件則包括所有的節(jié)點的唯一值即可凿掂。
#'數(shù)據(jù)預處理伴榔,構建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) + #'增加節(jié)點的標簽,reple避免節(jié)點重疊
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) + #'增加節(jié)點的標簽缠劝,reple避免節(jié)點重疊
labs(edge_width = "phone.call") + #'圖例標簽
theme_graph()
ggsave("fig3_test.png",pp)
ggraph.png
ggraph
的參數(shù)可以仔細調整潮梯,有很多疊加的圖層。
總結:根據(jù)自己的習慣惨恭,封裝成函數(shù)很好用秉馏。