可视化 生物信息学分析作图

网络-调用R包构建交互式网络可视化的Shiny App

2020-09-22  本文已影响0人  JeremyL
visNetwork shinyApp

本次会用到的三个关于网络的R包:visNetwork,igraph, geomnet;其中前两个R包均已经详细介绍过:

#构建网络节点和边数据

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 )对网络进行分析,获取每个节点所属组

#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"

#保存网络节点和边的数据;

save(nodes, file = "nodes.RData")
save(edges, file = "edges.RData")

#结果查看:

visNetwork(nodes, edges)
visNetwork-visNetwork()
visIgraph(graph)
visIgraph

#添加一些自定义操作

#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")
  )
)

##运行shiny

shinyApp(ui = ui, server = server)
visNetwork shinyApp

#原文:

Interactive Network Visualization with R

系列文章:
R语言进行网络分析的基础包 igraph
networkD3 绘制动态网络
网络-visNetwork包绘制炫酷的动态网络图

上一篇 下一篇

猜你喜欢

热点阅读