课程首页 | 课程简介 | 课程大纲 | 课程讲义 | 授课教师 | 网络可视化 | 课程建设动态 | 课程资讯 | 线上课程 | 头条推荐 
   
 

动态网络绘制工具 | D3 JavaScript Network Graphs from R!
2023-04-07 20:38 RCNS  RCNS

资料来源:

http://christophergandrud.github.io/networkD3/#dendro

Install

networkD3 works very well with the most recent version of RStudio (>=v0.99, download). When you use this version of RStudio, graphs will appear in the Viewer Pane. Not only does this give you a handy way of seeing and tweaking your graphs, but you can also export the graphs to the clipboard or a PNG/JPEG/TIFF/etc. file.

The package can be downloaded from CRAN.

Usage

For a full set of examples for each of the functions see this page.

Note: You are probably used to R’s 1-based numbering (i.e. counting in R starts from 1). However, networkD3 plots are created using JavaScript, which is 0-based. So, your data links will need to start from 0. See this data set for example. You can also use igraph to build your graph data and then use the igraph_to_networkD3 function to convert this data to a suitable object for networkD3 plotting.


> simpleNetwork

For very basic force directed network graphics you can use simpleNetwork. For example:

# Load package
library(networkD3)
# Create fake data
src <- c("A", "A", "A", "A",        
"B", "B", "C", "C", "D")
target <- c("B", "C", "D", "J",            
"E", "F", "G", "H", "I")
networkData <- data.frame(src, target)
# Plot
simpleNetwork(networkData)
A B C D E F G H I J

> forceNetwork

Use forceNetwork to have more control over the appearance of the forced directed network and to plot more complicated networks. Here is an example:

# Load data
data(MisLinks)
data(MisNodes)
# Plot
forceNetwork(Links = MisLinks, Nodes = MisNodes,            
Source = "source", Target = "target",            
Value = "value", NodeID = "name",            
Group = "group", opacity = 0.8)
Myriel Napoleon Mlle.Baptistine Mme.Magloire CountessdeLo Geborand Champtercier Cravatte Count OldMan Labarre Valjean Marguerite Mme.deR Isabeau Gervais Tholomyes Listolier Fameuil Blacheville Favourite Dahlia Zephine Fantine Mme.Thenardier Thenardier Cosette Javert Fauchelevent Bamatabois Perpetue Simplice Scaufflaire Woman1 Judge Champmathieu Brevet Chenildieu Cochepaille Pontmercy Boulatruelle Eponine Anzelma Woman2 MotherInnocent Gribier Jondrette Mme.Burgon Gavroche Gillenormand Magnon Mlle.Gillenormand Mme.Pontmercy Mlle.Vaubois Lt.Gillenormand Marius BaronessT Mabeuf Enjolras Combeferre Prouvaire Feuilly Courfeyrac Bahorel Bossuet Joly Grantaire MotherPlutarch Gueulemer Babet Claquesous Montparnasse Toussaint Child1 Child2 Brujon Mme.Hucheloup

From version 0.1.3 you can also allow scroll-wheel zooming by setting zoom = TRUE.

> sankeyNetwork

You can also create Sankey diagrams with sankeyNetwork. Here is an example using downloaded JSON data:

# Load energy projection data
# Load energy projection data
URL <- paste0(        
"https://cdn.rawgit.com/christophergandrud/networkD3/",        
"master/JSONdata/energy.json")
Energy <- jsonlite::fromJSON(URL)# PlotsankeyNetwork(Links = Energy$links, Nodes = Energy$nodes, Source = "source",             
Target = "target", Value = "value", NodeID = "name",             
units = "TWh", fontSize = 12, nodeWidth = 30)
Agricultural 'waste' Bio-conversion Liquid Losses Solid Gas Biofuel imports Biomass imports Coal imports Coal Coal reserves District heating Industry Heating and cooling - commercial Heating and cooling - homes Electricity grid Over generation / exports H2 conversion Road transport Agriculture Rail transport Lighting & appliances - commercial Lighting & appliances - homes Gas imports Ngas Gas reserves Thermal generation Geothermal H2 Hydro International shipping Domestic aviation International aviation National navigation Marine algae Nuclear Oil imports Oil Oil reserves Other waste Pumped heat Solar PV Solar Thermal Solar Tidal UK land based bioenergy Wave Wind

> radialNetwork

From version 0.2, tree diagrams can be created using radialNetwork or diagonalNetwork.

URL <- paste0(        
"https://cdn.rawgit.com/christophergandrud/networkD3/",        
"master/JSONdata//flare.json")

## Convert to list format
Flare <- jsonlite::fromJSON(URL, simplifyDataFrame = FALSE)
# Use subset of data for more readable diagram
Flare$children = Flare$children[1:3]
radialNetwork(List = Flare, fontSize = 10, opacity = 0.9)
flare analytics animate data cluster graph optimization Easing FunctionSequence interpolate ISchedulable Parallel Pause Scheduler Sequence Transition Transitioner TransitionEvent Tween converters DataField DataSchema DataSet DataSource DataTable DataUtil AgglomerativeCluster CommunityStructure HierarchicalCluster MergeEdge BetweennessCentrality LinkDistance MaxFlowMinCut ShortestPaths SpanningTree AspectRatioBanker ArrayInterpolator ColorInterpolator DateInterpolator Interpolator MatrixInterpolator NumberInterpolator ObjectInterpolator PointInterpolator RectangleInterpolator Converters DelimitedTextConverter GraphMLConverter IDataConverter JSONConverter
diagonalNetwork(List = Flare, fontSize = 10, opacity = 0.9)
flare analytics animate data cluster graph optimization Easing FunctionSequence interpolate ISchedulable Parallel Pause Scheduler Sequence Transition Transitioner TransitionEvent Tween converters DataField DataSchema DataSet DataSource DataTable DataUtil AgglomerativeCluster CommunityStructure HierarchicalCluster MergeEdge BetweennessCentrality LinkDistance MaxFlowMinCut ShortestPaths SpanningTree AspectRatioBanker ArrayInterpolator ColorInterpolator DateInterpolator Interpolator MatrixInterpolator NumberInterpolator ObjectInterpolator PointInterpolator RectangleInterpolator Converters DelimitedTextConverter GraphMLConverter IDataConverter JSONConverter

> dendroNetwork

From version 0.2, it is also possible to create dendrograms using dendroNetwork.

hc <- hclust(dist(USArrests), "ave")
dendroNetwork(hc, height = 600)
Florida North Carolina California Hawaii Maryland Alaska Washington Rhode Island Missouri Georgia Idaho Arizona New Mexico Delaware Mississippi South Carolina Oregon Massachusetts New Jersey Arkansas Tennessee Colorado Texas Nebraska Ohio Utah West Virginia Alabama Louisiana Illinois New York Michigan Nevada Wyoming Kentucky Montana Indiana Kansas Connecticut Pennsylvania Maine South Dakota North Dakota Vermont Minnesota Oklahoma Virginia Wisconsin Iowa New Hampshire

Interacting with igraph

You can use igraph to create network graph data that can be plotted with networkD3. The igraph_to_networkD3 function converts igraph graphs to lists that work well with networkD3. For example:

# Load igraph
library(igraph)

# Use igraph to make the graph and find membership
karate <- make_graph("Zachary")
wc <- cluster_walktrap(karate)
members <- membership(wc)

# Convert to object suitable for networkD3
karate_d3 <- igraph_to_networkD3(karate, group = members)

# Create force directed network plot
forceNetwork(Links = karate_d3$links, Nodes = karate_d3$nodes, 
             Source = 'source', Target = 'target', 
             NodeID = 'name', Group = 'group')
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

Output

Saving to an external stand alone HTML file

Use saveNetwork to save a network to a stand alone HTML file:

library(magrittr)
simpleNetwork(networkData) %>%
saveNetwork(file = 'Net1.html')

Including in an RMarkdown file

It is simple to include a networkD3 graphic in an RMarkdown file. Simply place the code to create the graph in a code chunk the same way you would any other plot. Checkout this simple example.

Including in Shiny web apps

You can also easily include networkD3 graphs in Shiny web apps.

In the server.R file create the graph by placing the function inside of render*Network, where the * is either Simple, Force, or Sankey depending on the graph type. For example:

output$force <- renderForceNetwork({
forceNetwork(Links = MisLinks, Nodes = MisNodes,            
Source = "source", Target = "target",            
Value = "value", NodeID = "name",            
Group = "group", opacity = input$opacity)
})

In the shinyUI part of your app.R file (for single-file Shiny apps) include *NetworkOutput (with * as before, but starting with a lowercase letter). The argument placed in this function should be the element specified with output, e.g.:

forceNetworkOutput("force")

You can run a simple example with the following code:

shiny::runGitHub('christophergandrud/networkD3-shiny-example')

Full source code for this example can be found here.

Saving as static PNG image

You can use RStudio to save static images of networkD3 plots as PNG files. Simply create your plot as usual in RStudio. The output should appear in the Viewer pane. Then click Export > Save as Image…. A new window will appear. You can use this window to manipulate the plot, resize it, and save the result as a PNG file.

RStudio-save-plot-as-image




Close Window
  读取内容中,请等待...

版权所有:Research Centre of Nonlinear Science 邮政编码:430073
E-mail:liujie@wtu.edu.cn 备案序号:鄂ICP备15000386号 鄂公网安备 42011102000704号