本次會用到的三個(gè)關(guān)于網(wǎng)絡(luò)的R包:visNetwork泽篮,igraph, geomnet谜疤;其中前兩個(gè)R包均已經(jīng)詳細(xì)介紹過:
- igraph:
- visNetwork:
- geomnet是一個(gè)基于ggplot2的網(wǎng)絡(luò)可視化包佃延,這兒只是使用geomnet中自帶的數(shù)據(jù)
#構(gòu)建網(wǎng)絡(luò)節(jié)點(diǎn)和邊數(shù)據(jù)
rm(list = ls())
# Libraries ---------------------------------------------------------------
library(visNetwork)
#devtools::install_github("cran/geomnet")
library(geomnet)
library(igraph)
library(dplyr)
# Data Preparation --------------------------------------------------------
#Load dataset
data(lesmis)
#Nodes
nodes <- as.data.frame(lesmis[2])
colnames(nodes) <- c("id", "label")
#id has to be the same like from and to columns in edges
nodes$id <- nodes$label
head(nodes)
id label
1 Myriel Myriel
2 Napoleon Napoleon
3 MlleBaptistine MlleBaptistine
4 MmeMagloire MmeMagloire
5 CountessDeLo CountessDeLo
6 Geborand Geborand
#Edges
edges <- as.data.frame(lesmis[1])
colnames(edges) <- c("from", "to", "width")
head(edges)
from to width
1 Myriel Napoleon 1
2 Myriel MlleBaptistine 8
3 Myriel MmeMagloire 10
4 MlleBaptistine MmeMagloire 6
5 Myriel CountessDeLo 1
6 Myriel Geborand 1
#使用社群檢測方法(Louvain )對網(wǎng)絡(luò)進(jìn)行分析,獲取每個(gè)節(jié)點(diǎn)所屬組
#Create graph for Louvain
graph <- graph_from_data_frame(edges, directed = FALSE)
#Louvain Comunity Detection
cluster <- cluster_louvain(graph)
cluster_df <- data.frame(as.list(membership(cluster)))
cluster_df <- as.data.frame(t(cluster_df))
cluster_df$label <- rownames(cluster_df)
#Create group column
nodes <- left_join(nodes, cluster_df, by = "label")
colnames(nodes)[3] <- "group"
#保存網(wǎng)絡(luò)節(jié)點(diǎn)和邊的數(shù)據(jù);
- 后面shiny程序會調(diào)用
save(nodes, file = "nodes.RData")
save(edges, file = "edges.RData")
#結(jié)果查看:
- visNetwork
visNetwork(nodes, edges)
- visIgraph: igraph包函數(shù)夷磕,使用graph對象作圖
- 輕松實(shí)現(xiàn)圖算法
- 快速處理具有數(shù)百萬頂點(diǎn)和邊的大型圖
- 允許通過R等高級語言進(jìn)行快速設(shè)計(jì)模型履肃。
visIgraph(graph)
#添加一些自定義操作
- visNodes:全局節(jié)點(diǎn)屬性設(shè)置
- visEdges:全局邊屬性設(shè)置
- visOptions:當(dāng)與網(wǎng)絡(luò)互動時(shí),網(wǎng)絡(luò)的反應(yīng)坐桩。例如尺棋,如果單擊一個(gè)節(jié)點(diǎn)會發(fā)生什么,出現(xiàn)提示等绵跷。
- visLayout:定義網(wǎng)絡(luò)的外觀膘螟。例如層次化的。此外碾局,我們可以提供一個(gè)種子(random Seed)荆残,保證網(wǎng)絡(luò)可重復(fù)生成。
- visIgraphLayout:使用igraph布局來計(jì)算坐標(biāo)和快速響應(yīng)數(shù)據(jù)變化擦俐。
#Shiny 整合
##global.R:
library(shiny)
library(visNetwork)
##server.R:
server <- shinyServer(function(input, output) {
output$network <- renderVisNetwork({
load("nodes.RData")
load("edges.RData")
visNetwork(nodes, edges) %>%
visIgraphLayout() %>%
visOptions(nodesIdSelection = TRUE, selectedBy = "group")
})
})
##ui.R:
ui <- shinyUI(
fluidPage(
visNetworkOutput("network")
)
)
##運(yùn)行shiny
shinyApp(ui = ui, server = server)
#原文:
Interactive Network Visualization with R
系列文章:
R語言進(jìn)行網(wǎng)絡(luò)分析的基礎(chǔ)包 igraph
networkD3 繪制動態(tài)網(wǎng)絡(luò)
網(wǎng)絡(luò)-visNetwork包繪制炫酷的動態(tài)網(wǎng)絡(luò)圖